MediumConcept

What is the difference between any, unknown and never in TypeScript?

Technology:
TypeScript
Experience:
Junior,
Mid-level

Quick answer

any turns off checking. unknown is a type-safe any: you must narrow it before use. never means a value cannot exist, used for exhaustive checks and functions that always throw.

Detailed explanation

A value typed any can be passed anywhere and you can read any property on it, so a typo compiles. unknown is what you give to untrusted input (JSON.parse, a network payload) until you prove its shape with typeof, in, or a type guard.

never is the empty set. A function with return type never does not return (throw or infinite loop). In a switch, assigning the leftover value to const _exhaustive: never = value makes the compiler fail when a new union member is added and not handled.

Example

typescript
function handle(x: unknown) {
  if (typeof x === "string") return x.toUpperCase();
  throw new Error("expected string");
}

function fail(message: string): never {
  throw new Error(message);
}
  • TypeScriptEasy

    What is TypeScript and why do we use it?

    TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. It catches type errors in the editor and at build time, and it documents the shape of data for the next person who reads the code.

    Intern 路 Junior 路 Types & Type System
  • TypeScriptMedium

    What are generics in TypeScript?

    Generics are type parameters: they let a function, class or type work with many types while keeping the relationship between inputs and outputs, instead of falling back to any.

    Junior 路 Mid-level 路 Types & Type System
  • TypeScriptMedium

    What are utility types in TypeScript like Partial, Pick and Omit?

    Utility types are built-in helpers that transform an existing type: Partial makes every field optional, Required the opposite, Pick keeps a set of keys, Omit removes them, and Record builds a key/value map.

    Junior 路 Mid-level 路 Types & Type System
  • TypeScriptMedium

    What is type narrowing in TypeScript?

    Narrowing is when TypeScript shrinks a wide type (such as a union) to a more specific type after a runtime check like typeof, instanceof, in, or a custom type guard.

    Mid-level 路 Senior 路 Types & Type System