Exhaustive switch in TypeScript
The never trick that makes the compiler reject an unhandled case.
type Shape = { kind: "circle"; r: number } | { kind: "square"; s: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.r ** 2;
case "square":
return shape.s ** 2;
default:
const exhausted: never = shape;
throw new Error(`unhandled: ${exhausted}`);
}
}
Keywords and builtins used here
MathShapecaseconstfunctionnevernumberreturnswitchthrowtype
The run, in numbers
- Lines
- 13
- Characters to type
- 307
- Tokens
- 87
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 55 seconds.
Step 4 of 4 in Narrowing, step 10 of 23 in Types & annotations.