Thuta Learning
TypeScript
IntermediateProgrammingIntermediate

unknown, never & Exhaustive Checking

TypeScriptLesson 725 min

What you'll walk away with

  • Explain the difference between any and unknown, and choose unknown for external data
  • Narrow an unknown value with typeof, instanceof and property checks
  • Recognise where never appears: throwing functions and branches after every case is handled
  • Write an exhaustive switch with const x: never = value or an assertNever() helper

Explain it simply

Explain it simply

Think of unknown as a parcel with no label. Anything can be inside, but you are not allowed to use it until you open it and check. TypeScript blocks calling methods, reading properties or doing maths on an unknown value until a check proves what it is. any is the opposite: it lets you treat the parcel as a phone without ever looking inside.

never is the type that says "no value can ever reach this spot". You use it like a checklist: once every case of a union has been handled, what is left must be never. If something is left over, TypeScript tells you straight away.

Problem → Why → Solution

The problem: code that fails silently

Two bugs hide in the code below. First, JSON.parse() returns any, so TypeScript happily accepts .toFixed() on amount even though it is a string, and the program crashes at runtime. Second, a few months later a teammate adds a wallet case to Payment. receiptLine() still compiles, but wallet payments now print nothing at all.

checkout.ts
type Payment =
  | { kind: "card"; last4: string }
  | { kind: "cash" }
  | { kind: "wallet"; provider: string }; // added later

function receiptLine(payment: Payment): void {
  switch (payment.kind) {
    case "card":
      console.log(`Card ending ${payment.last4}`);
      break;
    case "cash":
      console.log("Paid in cash");
      break;
    // no error: wallet payments are silently skipped
  }
}

const body = JSON.parse('{"amount":"12.50"}'); // type: any
console.log(body.amount.toFixed(2)); // compiles, then TypeError at runtime

Why didn't TypeScript catch these?

any switches type checking off entirely, so the compiler never looks at amount's real type. The switch lives in a void function, so a missing case is not an error either. The fix is to receive untrusted data as unknown and to end the switch with a never check.

Core concept: the top and bottom types

Picture each type as a set of possible values. boolean has two values, true and false; string has endlessly many. unknown is the biggest set, containing every value, so it is called the top type: anything can be assigned to an unknown variable. never is the empty set with no values at all, so it is called the bottom type.

unknown and any both accept anything, but they behave very differently when you use the value. any allows every operation and can be assigned to every other type, so a mistake spreads silently through the program. unknown allows nothing until you check. A check such as typeof input === "string" narrows input to string inside that branch. For objects you use instanceof (Date, Error) or property checks like typeof input === "object" && input !== null && "id" in input.

never shows up in two places. First, as the return type of a function that never returns normally because it always throws or loops forever. Second, in a branch where narrowing has ruled out every possibility: if Result is "ok" | "error" and both cases are handled, result has type never inside default.

That is the trick behind exhaustive checking. Writing const impossible: never = result; inside default compiles today. On the day someone adds a new case to the union, result is no longer never there, so that exact line becomes a compile error pointing at the code you still need to update. Nothing except never can be assigned to never.

The set view explains one more detail. never adds nothing to a union, so string | never is just string. That is why narrowing, which removes union members one by one, ends at never when nothing is left.

TypeWhat can be assignedWhat you can do without checking
anyanythinganything (checking is off)
unknownanythingnothing until you narrow
nevernothing except neverthis code is unreachable
Mental model: check in, check off
  1. Outside data arrives as unknown
  2. Check it with typeof / in / instanceof
  3. Handle every case of the union
  4. Leftover type is never = complete

unknown guards the way in; never confirms on the way out that no case was left behind.

General pattern

typescript
function handle(input: unknown) {
  if (typeof input === "string") { /* input is string here */ }
}

switch (value.kind) {
  case "a": /* ... */ break;
  case "b": /* ... */ break;
  default: {
    const unreachable: never = value; // errors if a case is missing
  }
}

The top half narrows an unknown with a runtime check. The bottom half is an exhaustive switch: when every case is handled, value is never inside default, and a missing case makes that assignment a compile error.

Example: from unknown input to a checked Result

Here toResult() accepts anything as unknown, checks it with typeof, and turns it into the Result union. show() handles every Result case and keeps a never check in the default branch. A never check prints nothing by itself, so the last lines pass three different inputs (42, "disk full" and null) through both functions to let you watch each branch run.

result.ts
type Result =
  | { kind: "ok"; value: number }
  | { kind: "error"; message: string };

function show(result: Result): string {
  switch (result.kind) {
    case "ok":
      return `Value: ${result.value}`;
    case "error":
      return `Error: ${result.message}`;
    default: {
      const impossible: never = result;
      throw new Error(`Unhandled result: ${JSON.stringify(impossible)}`);
    }
  }
}

function toResult(input: unknown): Result {
  if (typeof input === "number") return { kind: "ok", value: input };
  if (typeof input === "string") return { kind: "error", message: input };
  return { kind: "error", message: "unsupported input" };
}

console.log(show(toResult(42)));
console.log(show(toResult("disk full")));
console.log(show(toResult(null)));

Code breakdown

  1. Lines 1-3| { kind: "ok"; value: number }

    Result is a union whose members share a literal kind field. Checking kind tells TypeScript whether value or message exists.

  2. Line 12const impossible: never = result;

    Both cases are handled, so result is never here. Add a new case to Result and this line becomes a compile error.

  3. Line 13throw new Error(

    If bad data ever sneaks past the compiler (from any, for example), the function fails loudly instead of returning undefined.

  4. Line 18function toResult(input: unknown): Result {

    input is unknown: callers may pass anything, but the function body cannot use it without checking.

  5. Lines 19-21if (typeof input === "number") return { kind: "ok", value: input };

    Each typeof check narrows input to number or string. Every other value, including null, reaches the final fallback.

You should see
Value: 42
Error: disk full
Error: unsupported input
How a value travels
  1. input: unknown
  2. typeof check builds a Result
  3. switch (result.kind)

Case matches

formatted string

Case missing

compile error at never

assertNever(): a reusable helper

Instead of repeating a never variable and a throw in every switch, you can write a helper once. Its parameter type is never, so calling it is itself the exhaustiveness check. Its return type is also never, which tells the compiler the function never returns normally.

assert-never.ts
function assertNever(value: never): never {
  throw new Error(`Unexpected value: ${JSON.stringify(value)}`);
}

type Size = "s" | "m" | "l";

function price(size: Size): number {
  switch (size) {
    case "s": return 3;
    case "m": return 4;
    case "l": return 5;
    default: return assertNever(size);
  }
}

console.log(price("m"));

Caught errors are unknown too

In strict mode, err in catch (err) has type unknown (useUnknownInCatchVariables), because JavaScript can throw a string or any object. Check err instanceof Error before reading err.message.

In real projects

Where this shows up in real projects

Every edge of an application is a place for unknown: data from response.json(), JSON.parse() or localStorage.getItem(), messages from a queue, and files users upload. Receive them as unknown, check them with a validation function or a library such as zod, and only then pass them into the app. The rest of the code can then trust the data it receives.

Exhaustive checks pay off wherever the list of cases grows over time: Redux or useReducer action types, state machines such as order status (pending, paid, shipped, refunded), payment methods and notification channels. A commit that adds a case to the union automatically lists, as compile errors, every switch that must be updated, so nobody has to remember them during code review.

Common mistakes

Common mistakes

1. Casting unknown straight away with as

const user = data as User; quiets the compiler but performs no runtime check, which turns unknown back into any. Actually check the shape with typeof and in checks, or a validation function, before you rely on it.

2. Returning a fallback from default

Writing default: return "Unknown status"; means new cases fall into default and the compiler says nothing: the exhaustiveness check is gone. For union cases, keep default for the never check only.

3. Assuming a caught err is an Error

In strict mode, reading err.message directly fails with "'err' is of type 'unknown'". Rather than dodging it with (err as Error).message, check if (err instanceof Error) and handle the rest with String(err).

Best practices

Best practices

  • Type parameters for external data as unknown, not any.
  • End every function that switches over a union with assertNever().
  • Do not declare ordinary variables as never; use it only for exhaustiveness checks.

Mini challenge

Mini challenge: a traffic light state machine

Write a program that reads traffic light colours from unknown input, validates them, and computes the next colour with an exhaustive switch.

  • parseLight(input: unknown) returns a Light for "red", "yellow" or "green", and null otherwise
  • nextLight() cycles red → green → yellow → red
  • The default branch of nextLight() calls assertNever()
  • Try "green", "purple" and 7 and print each result
traffic-light.ts
type Light = "red" | "yellow" | "green";

function assertNever(value: never): never {
  // TODO: throw an Error that includes the unexpected value
}

function parseLight(input: unknown): Light | null {
  // TODO: narrow input to string, then accept only the three colours
}

function nextLight(light: Light): Light {
  // TODO: switch over light; call assertNever in default
}

// TODO: loop over ["green", "purple", 7] and print the results

Expected: green -> yellow purple -> invalid light 7 -> invalid light

Show hint

typeof input === "string" narrows input to string. Comparing it with === against each colour then narrows it to the literal type.

Show solution
traffic-light.ts
type Light = "red" | "yellow" | "green";

function assertNever(value: never): never {
  throw new Error(`Unexpected light: ${String(value)}`);
}

function parseLight(input: unknown): Light | null {
  if (typeof input !== "string") return null;
  if (input === "red" || input === "yellow" || input === "green") return input;
  return null;
}

function nextLight(light: Light): Light {
  switch (light) {
    case "red": return "green";
    case "green": return "yellow";
    case "yellow": return "red";
    default: return assertNever(light);
  }
}

for (const raw of ["green", "purple", 7]) {
  const light = parseLight(raw);
  console.log(light ? `${light} -> ${nextLight(light)}` : `${raw} -> invalid light`);
}

Quick quiz 1 / 3

What happens when you compile let v: unknown = "hi"; v.toUpperCase(); in strict mode?

Quick quiz 2 / 3

You add { kind: "wallet" } to the Payment union. The switch's default has const x: never = payment;. What happens?

Quick quiz 3 / 3

What is the correct return type for fail(msg: string), a function that always throws?

What to remember

  • unknown accepts every value but allows nothing until you narrow it; any switches checking off.
  • Receive untrusted data such as API responses, JSON.parse results and caught errors as unknown.
  • never is the type with no values: it appears in throwing functions and in branches with no cases left.
  • A never check or assertNever() in default turns every forgotten switch into a compile error when a union grows.

Type Compatibility — TypeScript

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.