Discriminated unions in TypeScript
A shared literal field that makes a union exhaustive.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "rect"; width: number; height: number }
| { kind: "square"; side: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "rect":
return shape.width * shape.height;
case "square":
return shape.side ** 2;
}
}
How it works
- Every member carries a distinct
kind. switchonkindnarrows to that member.- Covering all cases satisfies the return type.
Keywords and builtins used here
MathShapecasefunctionnumberreturnswitchtype
The run, in numbers
- Lines
- 15
- Characters to type
- 338
- Tokens
- 93
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 51 seconds.
Step 1 of 3 in Exhaustiveness & tests, step 9 of 12 in Type-level programming.