Discriminated unions

A discriminated union (also known as tagged unions or algebraic data types) is an advanced pattern that combines string literal types, union types, type guards, and types aliases.

Discriminated unions use a type guard to narrow union types based on tests of a discriminant property (a string literal type) and furthermore extend that capability to switch statements.

The following code snippet declares three types that share a string literal property named kind:

interface Cube {    kind: "cube";    size: number;}interface Pyramid {    kind: "pyramid";    width: number;    length: number;    height: number;}interface Sphere {    kind: "sphere";    radius: number;}

We then declare the union type of the three types declared in the preceding code snippet: ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.