Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a subset of a discriminated union based on a subset of the discriminator

Tags:

typescript

Typescript question:

Given a discriminated union type

interface A {
    discriminator: "A";
    data: string;
}

interface B {
    discriminator: "B";
    data: string;
}

interface C {
    discriminator: "C";
    num: number;
}

type U = A | B | C;
type Discriminator = U["discriminator"];

type AorB = SubsetOfU<"A"|"B">;

const f = (d:AorB) => d.data; // Should work

How do I write SubsetOfU to extract a subset of the union type?

I'm not after solving the specific case here, of course (would be just A|B), but a more complex scenario.

type SubsetOfU<K extends Discriminator> = ??????

like image 425
Pelle Avatar asked Jan 25 '23 18:01

Pelle


1 Answers

The Extract predefined type is already defined and does what you want:

type U = A | B | C;
type Discriminator = U["discriminator"];

type AorB = Extract<U, { discriminator: "A" | "B" }>;

const f = (d:AorB) => d.data;

Playground Link

like image 119
Titian Cernicova-Dragomir Avatar answered Feb 08 '23 22:02

Titian Cernicova-Dragomir