I’d like to get subtype from a union type via key field. Is it possible?
type T1 = {type: 'a', a1: string, a2: boolean}
type T2 = {type: 'b', b1: string}
type T3 = {type: 'c', c1: number}
// ...
type UnionT = T1 | T2 | T3 // ...
type SomeCoolType<T extends {type: string}, S extends T["type"]> = T // ... is it possible?
type SomeCoolType<UT, 'a'> // === {type: 'a', a1: string, a2: boolean}
type SomeCoolType<UT, 'b'> // === {type: 'b', b1: string}
// ...
>Solution :
What you are looking for is a built-in Extract utility type, that allows to retrieve members of a union if they extend the second argument:
type SomeCoolType<T extends { type: string }, S extends T['type']> = Extract<T, { type: S }>;
Usage:
type Case1 = SomeCoolType<UnionT, 'a'>; // === {type: 'a', a1: string, a2: boolean}
type Case2 = SomeCoolType<UnionT, 'b'>; // === {type: 'b', b1: string}