[Typescript] 93. Hard - Get Required

Implement the advanced util type GetRequired<T>, which remains all the required fields

For example

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

 

First thing need to understand how to know whether a prop is requried or not?

Idea: T[Key] extends Required<T>[Key] ? true: false

type GetRequired<T extends Record<PropertyKey, any>> = {
  [Key in keyof T]: T[Key] extends Required<T>[Key] ? true: false
}
type x = GetRequired<{ foo: number; bar?: string }>
/*
type x = {
    foo: true;
    bar?: false | undefined;
}
*/

 

With this Tip in mind, what we need to do is just check whether Key is required or not, if it is required, then keep it, if it is not requried, then set never.

/* _____________ Your Code Here _____________ */

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

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

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

 

posted @ 2022-11-10 21:57  Zhentiw  阅读(29)  评论(0编辑  收藏  举报