zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Typescript] 94. Hard - Get Optional

typescript get Hard optional 94
2023-09-14 08:59:11 时间

Implement the advanced util type GetOptional<T>, which remains all the optional fields

For example

type I = GetOptional<{ foo: number, bar?: string }> // expected to be { bar?: string }

 

/* _____________ Your Code Here _____________ */

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

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

type cases = [
  Expect<Equal<GetOptional<{ foo: number; bar?: string }>, { bar?: string }>>,
  Expect<Equal<GetOptional<{ foo: undefined; bar?: undefined }>, { bar?: undefined }>>,
]