Lessons · TypeScript · discriminated unions
A tag that tells the variants apart
A union of objects that each have a literal 'kind' field. switch on kind and each case knows its fields.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Events, actions, messages, API results: anything that is one of several shapes. The compiler checks that every case is handled.
How to think about it
What tag tells the variants apart? Give every variant the same tag field with a different literal value. switch on it. Add a default that assigns to a never so adding a variant later fails the build.
Worked example
type Msg = { kind: "text"; body: string } | { kind: "image"; url: string };Two shapes, one tag field with a different literal in each.function render(m: Msg): string {Takes either shape. switch (m.kind) {The tag decides the branch, and the compiler narrows inside each.case "text": return m.body;Here m is the text variant.
case "image": return `<img src=${m.url}>`;Here the image one.}
}
Your turn
Switch on the tag.
switch (shape.) {
case "circle": return shape.r;
}Solve one with the compiler running
The trap
Using a boolean or optional fields to tell variants apart. A literal tag is what lets the compiler narrow.
Practise discriminated unions on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.