any, unknown and never

Topic 4 of 4 in Everyday types7 min readIntermediateFree course

Overview

Most types describe a set of values: string is all the strings, boolean is true and false. A few special types are about the edges of the type system: a type that matches everything, one that matches nothing, and one that turns checking off. Knowing them — and which to avoid — is essential for writing safe TypeScript.

unknown, any and never. unknown is the top type: any value can go in, and you must check before using it. Below it sit the everyday types — string, number, boolean, object and so on. never is the bottom type: no value at all, for impossible cases. any sits outside the hierarchy: it switches checking off and should be avoided. Values flow upwards: a string can go where unknown is expected, never the other way without a check. any fits everywhere in both directions, which is exactly why it hides bugs.

any: checking switched off

A value of type any can be used as anything, and anything can be assigned to it:

TypeScript
let data: any = JSON.parse('{"port": 8080}');
data.server.port.toFixed();    // no error… crashes at run time
data = 42;
const s: string = data;        // no error, though it's a number

any is contagious: everything you read from an any is any too, so one any can quietly disable checking across a whole chain of code.

Where does any come from?

  • JSON.parse() and response.json() return any;
  • untyped libraries;
  • parameters without annotations when strict mode is off (noImplicitAny).

It exists for migrating JavaScript and for rare situations where the types really can’t be expressed. In application code, treat every any as a bug waiting to happen.

unknown: the safe alternative

unknown also accepts any value — but it doesn’t let you do anything with it until you’ve checked what it is:

TypeScript
const data: unknown = JSON.parse(text);

data.port;
// error TS18046: 'data' is of type 'unknown'.

if (typeof data === "object" && data !== null && "port" in data) {
  console.log(data.port);   // ✓ allowed after the checks
}

These checks are called narrowing (Type narrowing has the full toolkit):

TypeScript
function describe(value: unknown): string {
  if (typeof value === "string") return `text: ${value.toUpperCase()}`;
  if (typeof value === "number") return `number: ${value.toFixed(1)}`;
  if (Array.isArray(value)) return `array of ${value.length}`;
  if (value instanceof Date) return `date: ${value.toISOString()}`;
  return "something else";
}

Rule of thumb: when a value could be anything — parsed JSON, data from an API, caught exceptions, arguments to a generic logging function — type it unknown, not any. You’ll pay a few ifs, and get code that can’t crash on surprises.

A quick way to type parsed JSON safely:

TypeScript
const config: unknown = JSON.parse(text);

(For complex data, a validation library does the checks for you — Validating external data.)

Caught errors are unknown

In JavaScript you can throw anything — strings, numbers, objects. So TypeScript types the variable in catch as unknown (in strict mode):

TypeScript
try {
  riskyOperation();
} catch (error) {
  // error: unknown
  if (error instanceof Error) console.log(error.message);
  else console.log(String(error));
}

never: the impossible type

never is the type with no values at all. It shows up in two places.

Functions that never return

A function that always throws (or loops forever) never returns a value:

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

function getPort(config: { port?: number }): number {
  return config.port ?? fail("port is required");   // ✓ never fits anywhere
}

Because never has no values, it fits any type — number ?? never is just number.

Impossible branches

When narrowing has removed every possibility, what’s left is never:

TypeScript
function format(value: string | number) {
  if (typeof value === "string") return value;
  if (typeof value === "number") return value.toFixed(2);
  value;   // value: never — this line can't be reached
}

That’s the basis of exhaustiveness checking, one of TypeScript’s most useful tricks, covered in Discriminated unions.

void

void is the return type of functions that don’t return anything useful:

TypeScript
function log(message: string): void {
  console.log(message);
}

It differs from undefined in one way: a callback typed to return void may still return a value; the value is just ignored. That’s why [1, 2].forEach((n) => list.push(n)) is fine even though push returns a number.

Summary

Type Accepts Can use without checks? Use for
any everything yes — nothing is checked avoid; legacy code
unknown everything no — narrow first untrusted or unknown data
never nothing — functions that throw, impossible cases
void (no useful value) — functions that return nothing

Rule: reach for unknown, never any. If you find yourself writing any, ask what you’d check before using the value — then write those checks.

Exercise

Replace any with unknown

The starter parses settings with any and crashes at run time on bad input. Rewrite it safely: parseJson(text: string): unknown returns the parsed value, or undefined if JSON.parse throws. readPort(value: unknown): number returns value.port only if value is an object (not null) with a numeric port property — otherwise it calls fail("missing port"), a function with return type never that throws an Error. Test it with the three inputs in the starter, catching and printing errors, so the output is 8080, Error: missing port, Error: missing port.

TypeScript
function parseJson(text: string): any {
  return JSON.parse(text);
}

function readPort(settings: any): number {
  return settings.server.port;
}

for (const text of ['{"port": 8080}', '{"port": "80"}', "not json"]) {
  console.log(readPort(parseJson(text)));
}

Summary

  • any switches type checking off for a value — anything goes, and errors spread silently. Avoid it.
  • unknown also accepts any value, but you must narrow it (typeof, instanceof, in) before using it.
  • Use unknown for data you don’t control: JSON, caught errors, user input.
  • never is the type with no values: functions that always throw, and code paths that can’t happen.
  • void is the return type of functions that don’t return a useful value.