banner
SlhwSR

SlhwSR

热爱技术的一名全栈开发者
github
bilibili

ts Assertion Tips and Tricks

When asked to implement type extraction, if you want to extract the name and age properties from Goose, you would think of the following methods:

type Gooose={
  name:string
  age:number
  getCuurent:()=>void
}

type FilterObj<T,U>={
 [P in keyof T]:T[P]
}

// At this time, FilterObj accepts the traversal of keys, but we are always unsure of the type of the extracted key, so we assert it:

type Gooose={
  name:string
  age:number
  getCuurent:()=>void
}

type FilterObj<T,U>={
 [P in keyof T as Exclude<P,U>]:T[P]
}

Suppose I pass age as the property

const some:FilterObj<Gooose,'getCuurent'>={name:"sanm",age:99}

const some2:FilterObj=<Goose,'name'| 'age'>={
getcurrent:()=>alert("!!")
}

Mission accomplished👩‍🎤

Method 2#

Filtering indexes based on value types

type Gooose={
  name:string
  age:number
  getCuurent:()=>void
}
// Because never is a subtype of any type, the key automatically disappears when merged
type FilterOptions<T,U>={
  [P in keyof T]:T[P] extends U? never:P
}[keyof T]  // Finally extract the union type

type oo=FilterOptions<Gooose,Fucnction>
// oo returns the type
 {getCurrent:never,name:string,age:number}

// Similarly
type pp=FilterOptipns<Gooose,Function|age>
// Returns {age:never,getCurrent:never,name:string}

Because the final extraction result is a union type 'name' | 'age ' | 'getCurrent'

type resut =Pick<Goose,pp>

That is, the corresponding type is extracted, mission accomplished🙂

Method 3#

type Gooose={
  name:string
  age:number
  getCuurent:()=>void
}

type Omit<T,U>=Pick<T,Exclude<keyof T,U>>

type try=Omit<Gooose,'name' | 'age'>
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.