Reputation: 1147
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?
Upvotes: 4
Views: 3351
Reputation: 32146
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">
Upvotes: 7