[Typescript] 94. Hard - Get Optional
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 }>>,
]