Home > Software engineering >  In typescript Pick utility does not create all subsets of object type
In typescript Pick utility does not create all subsets of object type

Time:11-12

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.

CodePudding user response:

Is this what you want?

type person = {name: string, age: number, dob: Date};
type PickOptional<T, K extends keyof T> = {[k in K]?:T[k]}

type Test = PickOptional<person,'name' | 'dob'>
let person1: Test = {name: 'test1'}

CodePudding user response:

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 Picks.

type P1 = PickUnion<Person, 'name' | 'dob'> & Partial<Person>

// valid
const person1: P1 = { name: 'test1' }
const person2: P1 = { dob: new Date() }

// invalid
const person3: P1 = {}

Playground

  • Related