TypeScript 7 reference · Type Operators and Keywords
TypeScript never Keyword
The type with no values: for functions that never return, impossible branches, and exhaustiveness checks.
TypeScript 7 Since 2.0
Examples
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 unreachable: never = shape; // errors if a new kind is added and not handled
return unreachable;
}
}
}
console.log(area({ kind: "square", s: 3 }));
Output
9
function fail(message: string): never {
throw new Error(message);
}
try {
fail("not implemented");
} catch (e) {
console.log((e as Error).message);
}
Output
not implemented
Version history
| Version | Change |
|---|---|
| TypeScript 2.0 | Added |
Related
unknown· The type-safe 'anything': a value of type unknown must be narrowed (checked) before you can use it, unlike any.Exclude<UnionType, ExcludedMembers>· Remove members from a union type. Exclude<'a' | 'b' | 'c', 'a'> is 'b' | 'c'.- TypeScript keyof, typeof and Indexed Access · tutorial