Chris Talman
Chris Talman

Reputation: 1169

Pick With Optional Keys

In TypeScript, is it possible to have a Pick-style utility type in which keys can be specified which may or may not be available on the picked object type? For example:

interface Alpha
{
    a: boolean;
    b: boolean;
}

type Picked = OptionalPick<Alpha, 'a' | 'c'>; // { a: boolean }

Upvotes: 6

Views: 4447

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249756

Yes it is possible, we can define the second parameter K as just extending PropertyKey and then use Extarct to extract from keyof T any properties that are in the union K:

interface Alpha
{
    a: boolean;
    b: boolean;
}

type OptionalPick<T, K extends PropertyKey> = Pick<T, Extract<keyof T, K>>
type Picked = OptionalPick<Alpha, 'a' | 'c'>; 

Play

Upvotes: 8

Related Questions