logoProsperBao

Optional Keys

2022-05-05 03

题目来源(type-challenges)

问题

实现高级util类型OptionalKeys<T>,该类型将所有可选键合并为一个并集。

例如:

type case1 = OptionalKeys<{ a: number; b?: string }> // 'b'
type case2 = OptionalKeys<{ a: undefined; b?: undefined }> // 'b'
type case3 = OptionalKeys<{ a: undefined; b?: undefined; c?: string; d?: null }> // 'b' | 'c' | 'd'
type case4 = OptionalKeys<{}> // never

解答

type OptionalKeys<T> = keyof {
  [K in keyof T as T[K] extends Required<T>[K] ? never : K]: T[K]
}

拆分

  1. Get Optional Required Keys 类似