unknown, any and never in TypeScript
unknown demands a check, any waives them, never means it cannot happen.
function parse(raw: unknown): number {
if (typeof raw === "number") return raw;
if (typeof raw === "string") return Number.parseFloat(raw);
throw new TypeError(`cannot parse ${typeof raw}`);
}
function fail(message: string): never {
throw new Error(message);
}
type Shape = { kind: "circle"; r: number } | { kind: "square"; side: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.r ** 2;
case "square":
return shape.side ** 2;
default: {
const impossible: never = shape;
return fail(`unhandled ${JSON.stringify(impossible)}`);
}
}
}
console.log(parse("2.5"), area({ kind: "square", side: 3 }));
How it works
unknownis the safe top type: narrow it before use.neveris the empty type, returned by a function that always throws.- An exhaustive switch assigns the leftover to
never.
Keywords and builtins used here
JSONMathNumberShapecaseconstdefaultfunctionifnevernumberparseFloatreturnstringswitchthrowtypeunknown
The run, in numbers
- Lines
- 26
- Characters to type
- 656
- Tokens
- 183
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 122 seconds.
Step 1 of 2 in The awkward types, step 5 of 23 in Types & annotations.