Thuta Learning
TypeScript
IntermediateProgrammingintermediate

unknown, never & Exhaustive Checking

TypeScriptLesson 7

What you'll walk away with

  • Explain the runtime-value and compile-time-type relationship in unknown, never & Exhaustive Checking
  • Test unsafe input and edge cases in strict mode
  • Write maintainable TypeScript contracts

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

typescript
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;
    }
  }
}
You should see
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 CompatibilityTypeScript

Easy traps

  • Assuming a successful TypeScript compile proves API data and runtime behavior are valid.
  • Silencing an error with any, as, or a non-null assertion instead of repairing the contract.

Hands-on Exercise

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.

You'll know it worked when: Adding an unhandled variant becomes a compile-time error.

unknown, never & Exhaustive Checking | Thuta Learning