Treat unknown, never & Exhaustive Checking as a model of possible JavaScript runtime values, control-flow narrowing, nullability, and exhaustive checking—not merely annotation syntax. Prefer inference and begin unsafe input as unknown.
Build a Complete Mental Model
Treat unknown, never & Exhaustive Checking as a model of possible JavaScript runtime values, control-flow narrowing, nullability, and exhaustive checking—not merely annotation syntax. Prefer inference and begin unsafe input as unknown.
Apply It in Production TypeScript
Type-check an original unknown, never & Exhaustive Checking example in strict mode, then test valid values, null/undefined, malformed API data, a new union variant, and module boundaries. Fix the contract or validation instead of silencing errors with assertions or any.
After This Lesson
type Result = { kind: 'ok'; value: number } | { kind: 'error'; message: string };
function show(result: Result): string {
switch (result.kind) {
case 'ok': return String(result.value);
case 'error': return result.message;
default: {
const impossible: never = result;
return impossible;
}
}
}Adding an unhandled variant becomes a compile-time error.Try It Yourself
Type-check an original unknown, never & Exhaustive Checking example in strict mode, then test valid values, null/undefined, malformed API data, a new union variant, and module boundaries. Fix the contract or validation instead of silencing errors with assertions or any.
Type Safety Warning
Assuming a successful TypeScript compile proves API data and runtime behavior are valid.
Type Compatibility — TypeScript