TypeScript Tutorial · TypeScript Basics · Lesson 12 of 25

TypeScript any, unknown and never

The escape hatch, the safe top type and the empty type.

any — turn off checking

any disables type checking for a value. It spreads silently and hides bugs; avoid it (enable noImplicitAny, which strict does).

unknown — the safe alternative

unknown accepts any value, but you must narrow it before using it. Use it for data from outside your program: JSON.parse, API responses, catch clauses:

Example 1Try it yourself
const fromApi: unknown = JSON.parse('{"count": 3}');

function unsafe() {
  // @ts-expect-error — 'fromApi' is of type 'unknown'.
  return fromApi.count;
}

if (typeof fromApi === "object" && fromApi !== null && "count" in fromApi) {
  console.log("count is", fromApi.count);
}

const risky: any = "hello";
console.log(typeof risky.toFixed);  // the compiler allows anything on 'any' — this would crash if called

Output

count is 3
undefined

never — exhaustiveness checks

never is the type with no values. Assigning a value to never in a default branch makes the compiler tell you when you forgot to handle a case:

Example 2Try it yourself
type Shape = { kind: "circle"; r: number } | { kind: "square"; side: number };

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.r ** 2;
    case "square":
      return shape.side ** 2;
    default: {
      const unreachable: never = shape;  // compile error here if a new kind is added
      return unreachable;
    }
  }
}
console.log(area({ kind: "square", side: 3 }).toFixed(1), area({ kind: "circle", r: 1 }).toFixed(2));

Output

9.0 3.14

Test yourself

Which type should you use for a value whose type you don't know yet, but want to check safely?

  1. any
  2. unknown
  3. never
  4. object
Show answer

Answer: unknown