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> = ??????
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With