Skip to the workspace
Pebellslearn by building
TypeScript Interfaces  ›  Lesson

any, unknown and never

unknown 12 minany turns checking off, unknown accepts anything but must be narrowed before use, and never is the type with no values at all.

typescript / any, unknown and never

Explore each scene at your own pace.

01 · The rule

The rule

any, unknown and never

any turns checking off, unknown accepts anything but must be narrowed before use, and never is the type with no values at all.

Track unchecked input through validation and distinguish it from an impossible state.

Three special types sit at the edges of TypeScript's type system. any and unknown both accept every value, yet one is dangerous and the other is safe. never accepts no value at all, and is surprisingly useful. Knowing which is which keeps your checks honest.

The rule

any trusts everything, unknown trusts nothing yet, never has no values.

any — accepts every value and allows every operation. Checking is switched off:

let saved: any = JSON.parse(text);
saved.tasks.forEach((t: any) => t.titel.trim()); // compiles, may crash
const n: number = saved;                          // also compiles

any also leaks: assign it to a typed variable and the compiler believes you.

unknown — also accepts every value, but allows nothing until you check what it is:

let data: unknown = JSON.parse(text);
data.tasks;                     // error: data is unknown

if (typeof data === "object" && data !== null && "tasks" in data) {
  // data is now known to be an object with a tasks property
}

unknown is the right type for things that come from outside — parsed JSON, user input, caught errors (catch (e) is unknown in strict mode). You pay for safety with a check, which is exactly the point.

never — the type with no values. You meet it in three places:

  • A function that never finishes normally, such as one that always throws: function fail(msg: string): never { throw new Error(msg); }
  • Impossible types, like string & number.
  • What is left after narrowing has ruled out every possibility — which gives an exhaustive check:
type Status = "todo" | "doing" | "done";

function label(s: Status): string {
  switch (s) {
    case "todo":  return "To do";
    case "doing": return "In progress";
    case "done":  return "Done";
    default:
      const unreachable: never = s;
      return unreachable;
  }
}

Every case is handled, so in default the type of s is never. Add "blocked" to Status and forget a case: now s could be "blocked", which cannot be assigned to never, and the compiler points straight at the missing case.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.