Issue
Try to produce subset of object
type person = {name: string, age: number, dob: Date};
type p1 = Pick<person, 'name' | 'dob'>
but get error ("error dob is missing") if
person1: p1 = {name: 'test1'}
I am wondering what is the best way to create all subsets of type person
in Typescript.
Solution
The normal Pick
utility type is probably not what you want as it produces a type containing all the properties specified in the union of keys. We can make our custom PickUnion
which behaves differently.
type PickUnion<T, K extends keyof T> =
K extends K
? Pick<T, K>
: never
It works by distributing the result over K
which leads to a union of Pick
s.
type P1 = PickUnion<Person, 'name' | 'dob'>
// valid
const person1: P1 = { name: 'test1' }
const person2: P1 = { dob: new Date() }
// invalid
const person3: P1 = {}
Answered By - Tobias S.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.