banner
SlhwSR

SlhwSR

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

Implementing various type utilities in TypeScript

  1. Implement Partial:
typeA={name:string,age:string}

type Partial<T>={
[p in keyof T]?:T[p]
}
//i.e. type C=Partial<A>
  1. Implement pick to extract partial types
type example={name:string,age:number,address:string}
type Pick<T,U extends keyof T>={
  [P in U]=T[P]
}
const tiqu:Pick<example,"name"|"age">={}
  1. Implement Extract
type Extract<T,U>=T extends U? T: never

type A=string | number | boolean
type B=string | number

type C=Extract<A,B>
const result:C="214214"
const result2:C=444

  1. Implement Exclude, same idea as Extract
type Exclude<T,U>=T extends U?never :T
type A=string | number | boolean
type B=string | number

type C=Exclude<A,B>
const result:C="214214"  //error
const result2:C=true
  1. Implement Record
type Record<K extends string|number|symbol,V>={
[P in K]:V
}
type EX=Record<'name'|'age',string|number>
const res:EX={name:"张三",age:999}
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.