Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a union type of picked keys

Tags:

typescript

Given an interface, eg:

interface A {
    AA : string
    AB : number
}

I would like a type that is a union of every possible picked type, eg:

type B = Pick<A, "AA"> | Pick<A,"AB"> 

Or, if not familiar with Pick:

type B = {AA: string} | {BB : number}

I don't want to have to write it out manually like above though. I'd like to be able to write some kind of generic type or function that will do it for me, eg

type B = OneOf<A>

How would 'OneOf' be written, or what is the closest current approximation/workaround in typescript?

like image 519
Rene Wooller Avatar asked Mar 07 '23 19:03

Rene Wooller


1 Answers

How about something like this:

type OneOf<T> = {[K in keyof T]: Pick<T, K>}[keyof T];

Using that structure, your example would look like this:

interface A {
    AA: string;
    AB: number;
}

declare var x: OneOf<A>;

// x now has type:
// Pick<A, "AA"> | Pick<A, "AB">
like image 187
CRice Avatar answered Mar 15 '23 09:03

CRice