serendipityApe / javascriptPromotion

资深前端必备的编码问题
3 stars 0 forks source link

实现Omit<T, K> #19

Open serendipityApe opened 2 years ago

serendipityApe commented 2 years ago

答题

implement Omit<T, K>

例子

omit<T,K>在T中过滤K,并返回过滤后的新类型

type Foo = {
  a: string
  b: number
  c: boolean
}

type A = MyOmit<Foo, 'a' | 'b'> // {c: boolean}
type B = MyOmit<Foo, 'c'> // {a: string, b: number}
type C = MyOmit<Foo, 'c' | 'd'>  // {a: string, b: number}

答题

// your code here, please don't use Omit<T, K> in your code
type MyOmit<T, K extends keyof any> = {
  //Exclude操作联合类型
  [key in Exclude<keyof T, K>]: T[key]
}

补充

Exclude只能操作联合类型,即:type union= 'a' | 'b' | 'c'