← TypeScript

Basic · 11 of 13 · 13 min read

any, unknown, never and void

The four special types, where each sits in the assignability hierarchy, and why any is contagious in a way unknown is not.

  • Type annotations

Four types that are not about data so much as about the type system itself: the one that switches checking off, the one that insists on it, the one with no values at all, and the one that means “ignore the result”.

unknown the top type string User never the bottom type arrows point to "assignable to" any both directions outside the order
Everything is assignable to unknown and never is assignable to everything — which is why a fully narrowed union becomes never and why that makes exhaustiveness checking work. any is not in the hierarchy at all: it is assignable in both directions, which is exactly what makes it dangerous.

any switches checking off

let value: any = "hello";

console.log(value.length);        // no error
console.log(value.toFixed(2));    // no error — and a crash
console.log(value.anything.at.all); // still no error

const n: number = value;          // assignable to anything

It is not “a value of unknown type” — it is “stop checking this”. And it spreads:

const data: any = JSON.parse('{"name":"Ana"}');
const user = data.user;            // any
const name = user.naem;            // any — the typo is invisible
console.log(name.toFixed());       // compiles, throws

Everything read off an any is also any, so one at the top of a chain disables checking for everything below it. That contagion is why a single any in the wrong place costs far more than it looks like it should.

unknown insists

let value: unknown = "hello";
value = 42;                       // accepts anything, like any

// console.log(value.length);     // 'value' is of type 'unknown'
// const n: number = value;       // not assignable to 'number'

if (typeof value === "string") {
  console.log(value.length);      // narrowed — and now safe
}

Same values in, and nothing out until you prove the type. That makes it the right annotation for anything crossing into the program:

interface User { id: number; name: string }

function isUser(value: unknown): value is User {
  return (
    typeof value === "object" && value !== null &&
    typeof (value as User).id === "number" &&
    typeof (value as User).name === "string"
  );
}

const parsed: unknown = JSON.parse('{"id":1,"name":"Ana"}');
if (isUser(parsed)) console.log(parsed.name.toUpperCase()); // "ANA"
else console.log("unexpected payload");
any unknown
Accepts any value yes yes
Assignable to other types yes only unknown and any
Members readable without narrowing yes no
Spreads through expressions yes no
Errors it causes appear far from the cause at the use

never has no values

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

function loop(): never {
  while (true) {}                 // never finishes
}

// const impossible: never = 1;   // nothing is assignable to never
type Nothing = string & number;    // never — no value is both

The useful part is what the compiler does with it. never is the empty union, so a fully narrowed value becomes never — which is how exhaustiveness checking works:

type Shape = { kind: "circle" } | { kind: "square" };

function assertNever(value: never): never {
  throw new Error(`unhandled: ${JSON.stringify(value)}`);
}

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle": return 1;
    case "square": return 2;
    default: return assertNever(shape); // adding a member errors HERE
  }
}

console.log(area({ kind: "circle" })); // 1

It also disappears from unions and marks dead code:

type A = string | never;   // string
function f(): never { throw new Error("x"); }

function g() {
  f();
  // console.log("unreachable"); // the compiler knows this cannot run
}
console.log(typeof g);

void means “ignore the result”

function log(message: string): void {
  console.log(message);           // completes, returns nothing
}

console.log(log("hi")); // undefined

void is not quite undefined. A function returning anything is assignable to a void-returning type, which is the rule that makes everyday callbacks compile:

type Handler = () => void;

const handler: Handler = () => 42;  // allowed — the result is just ignored

const target: number[] = [];
[1, 2].forEach((n) => target.push(n)); // push returns a number nobody wants
console.log(target);                    // [1, 2]

// Declaring void directly is still checked:
// function f(): void { return 42; }    // not assignable to void
void never undefined
The function completes does not complete completes
Returns nothing usable nothing, ever the value undefined
As a variable type nearly useless holds nothing holds undefined
Anything assignable to it as a return yes no no

Where each belongs

// unknown — at every boundary
async function load(url: string): Promise<unknown> {
  return (await fetch(url)).json();
}

// never — for exhaustiveness and for functions that always throw
function unreachable(value: never): never {
  throw new Error(`unexpected: ${String(value)}`);
}

// void — for callbacks whose result nobody reads
type Listener = (event: string) => void;

// any — rarely, locally, with a comment saying why
// eslint-disable-next-line @typescript-eslint/no-explicit-any
declare function legacyPlugin(options: any): void;
console.log(typeof unreachable, typeof legacyPlugin);

The rule of thumb: reach for unknown first and narrow. If narrowing is genuinely impossible — an untyped library, a dynamic plugin — then any, kept as small as you can make it.

Common mistakes

Using any to get past an error

Mistake. Annotating a parsed response as any because typing it is fiddly. Why it fails. Everything derived from it is unchecked too, so the real failure appears somewhere unrelated and much later. What to do instead. unknown plus a guard. The checking you were avoiding is the checking that was going to catch the bug.

Treating unknown as a cast you have to fight

Mistake. (value as SomeType).property everywhere, to get past the compiler. Why it fails. The assertion is just any with extra typing — nothing is verified. What to do instead. Narrow once with a guard, and the whole scope below it is typed.

Expecting void to mean the function returns nothing

Mistake. Being surprised that () => 42 satisfies () => void. Why it fails. The rule is about the caller ignoring the result, and it exists so that arr.forEach(x => arr2.push(x)) compiles. What to do instead. Use : void on the declaration itself when the body genuinely must not return a value — there it is checked.

Check yourself

3 questions from the bank on what you just read. Answering here does not affect your quiz history.

What does unknown give you that any does not?

What is the difference between a function returning void and one returning never?

An any does not stay where you put it — it travels through every expression it touches.

Why does the compiler accept user.naem.toFixed() here?

Code sample
const data: any = JSON.parse('{"name":"Ana"}');
const user = data.user;
console.log(user.naem.toFixed());
Practise Type annotations →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.