Building Discriminated Unions
Tag union members with a shared discriminant property.
What Is a Discriminated Union?
A discriminated union is a union of object types that all share a common literal property called the discriminant. That shared tag lets TypeScript tell the members apart.
// The shared "kind" property is the discriminant
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
type Shape = Circle | Square;The Discriminant Property
The discriminant must be a literal type (like "circle"), not a wide type like string. Each member gets its own unique literal value.
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
const c: Circle = { kind: "circle", radius: 10 };
console.log(c.kind); // "circle"All lessons in this course
- Building Discriminated Unions
- Narrowing on the Discriminant
- Exhaustiveness Checking with never
- Modeling State Machines