[Typescript] 96. Hard - Optional Keys

Implement the advanced util type OptionalKeys<T>, which picks all the optional keys into a union.

 

/* _____________ Your Code Here _____________ */

type OptionalKeys<T extends Record<PropertyKey, any>> = keyof {
  [Key in keyof T as T[Key] extends Required<T>[Key] ? never: Key]: any
}


/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'

type cases = [
  Expect<Equal<OptionalKeys<{ a: number; b?: string }>, 'b'>>,
  Expect<Equal<OptionalKeys<{ a: undefined; b?: undefined }>, 'b'>>,
  Expect<Equal<OptionalKeys<{ a: undefined; b?: undefined; c?: string; d?: null }>, 'b' | 'c' | 'd'>>,
  Expect<Equal<OptionalKeys<{}>, never>>,
]

 

posted @ 2022-11-11 00:11  Zhentiw  阅读(16)  评论(0编辑  收藏  举报