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 }>>,
]
标签:Typescript,_____________,Get,type,Required,Key,93,foo,GetRequired From: https://www.cnblogs.com/Answer1215/p/16878946.html