any, unknown, never, and void

Beginner · 10 min

The four special types: `any` switches checking off, `unknown` is the safe top type, `never` is the empty type, and `void` means no useful return.

Before thisType annotations and type inference

TypeScript with Benny Code · 10 min

any, unknown, never, and void

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by TypeScript with Benny CodeReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • `any` turns type checking off for a value: anything can be assigned to it, it can be assigned to anything, and every operation on it compiles, so mistakes pass silently and spread to whatever it touches.
  • `unknown` also accepts any value, but you cannot do anything with it until you have checked what it is; it is the type to use for data whose shape you don't know yet.
  • `never` is the type with no values at all; it is the return type of a function that always throws or never finishes, and the type left over when every possibility has been ruled out.
  • `void` is the return type of a function whose return value should be ignored; a function type returning `void` still accepts callbacks that happen to return something.
  • Under `strict`, a missing annotation that would have produced an implicit `any` is an error, so `any` only appears where someone wrote it on purpose or where a library returns it.

Types that describe edges, not values

string, number, and object types each describe a kind of value. Four types in TypeScript are different: they describe the edges of the type system. One means “stop checking”, one means “could be anything, prove it before use”, one means “there is no value here”, and one means “there is a result, but ignore it”. You meet all four within the first week of real code, often in error messages, so it helps to know exactly what each one claims.

A useful way to picture types is as sets of values. boolean is the set {true, false}. string is the set of every string. With that picture, unknown is the set of every value, and never is the empty set. any sits outside the picture entirely, and void is about function results rather than values.

any: the off switch

any tells the compiler to stop checking a value:

let data: any = JSON.parse('{"name":"Ada"}');

data.name.toUpperCase(); // compiles
data.nmae.toUpperCase(); // also compiles, then crashes at runtime
const total: number = data; // compiles too

Every operation on any compiles, and any is assignable to every other type. That second part is what makes it dangerous: the unchecked value leaks into variables that look fully typed. total above claims to be a number, and nothing verified it.

any exists for migration, where a JavaScript codebase is typed gradually, and for the rare spot where the types genuinely can’t be expressed. Under strict, noImplicitAny makes sure it only shows up when written explicitly; a parameter left unannotated becomes an error instead of a silent any. You will still meet any from older library types and from built-ins like JSON.parse.

unknown: accept anything, trust nothing

unknown also accepts every value, but it lets you do nothing with one until you’ve checked what it is:

function shout(value: unknown) {
  value.toUpperCase(); // Error: 'value' is of type 'unknown'.

  if (typeof value === "string") {
    return value.toUpperCase(); // fine: value is string in here
  }
  return String(value);
}

Think of it as a parcel from an unknown sender at a mail room. The room accepts it, but nobody plugs it in until someone has opened it and checked what it is. The typeof check is narrowing, which has a whole group of its own; here, the point is that the compiler insists on it.

Reach for unknown wherever data arrives without a trustworthy type: parsed JSON, message events, values from storage. Under strict, the variable in a catch (err) block is also unknown, since anything at all can be thrown. The validating untrusted data lesson shows how to turn unknown into a real type properly.

never: no value at all

never is the type that has no values. Nothing is assignable to it, which sounds useless until you see where it appears.

The first place is functions that never return normally:

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

function parsePort(input: string): number {
  const port = Number(input);
  if (Number.isNaN(port)) fail(`Not a port: ${input}`);
  return port;
}

Because fail returns never, the compiler knows control does not continue past that call. An infinite event loop would also return never.

The second place is where every option has been ruled out. If a value is "a" | "b" and you’ve handled both, what’s left is never:

function check(letter: "a" | "b") {
  if (letter === "a") return 1;
  if (letter === "b") return 2;
  const leftover: never = letter; // fine: nothing remains
  return leftover;
}

Try to put a real value into a never slot and you get Type 'string' is not assignable to type 'never'. Using that error deliberately, to catch a forgotten case when a union grows, is called exhaustiveness checking and has its own lesson.

void: there is no useful result

void is for functions whose return value should be ignored:

function logVisit(path: string): void {
  console.log(`visited ${path}`);
}

At runtime such a function returns undefined, but void says something slightly different: “don’t use the result”. That difference matters for callback types:

const seen: number[] = [];
[1, 2, 3].forEach((n) => seen.push(n)); // fine, though push returns a number

type Listener = () => void;
const onClick: Listener = () => 42; // also fine

forEach declares its callback as returning void, meaning it will throw the result away. Throwing away a number is harmless, so a callback that returns one is allowed. The strict rule applies only when you annotate a function declaration itself as : void; then a return 42 inside it is an error. The parameter and return types lesson covers that side.

Picking between them

When you don’t know a value’s type, use unknown, not any. When a function can’t return, use never. When a function returns nothing worth reading, use void. Treat each any you write as a small debt you mean to pay off.

About the video

Benny Code’s video is the rare one that covers all four types in one place, with a chapter for each, and it uses the same distinctions as this lesson: any disables checking, unknown makes you narrow first, never has no values, and void marks an ignored result. The delivery is steady rather than lively, so the chapter markers are handy for jumping to the type you need. Andrew Burgess’s video in the links frames unknown and never as the top and bottom of the type hierarchy, which is worth watching once the basics here are clear.

Check yourself

  1. 01Both `any` and `unknown` accept every value. What is the practical difference?

    With `any`, the compiler lets you do anything with the value, such as calling methods or reading properties, without checking. With `unknown`, it lets you do nothing until you narrow the value, for example with `typeof value === "string"`. `unknown` forces the check that `any` lets you skip.

  2. 02Why is `never` the right return type for `function fail(msg: string) { throw new Error(msg); }`?

    The function can never return normally; every call ends in a throw. `never` says exactly that, and it lets the compiler treat any code after a call to `fail` as unreachable, which is useful when narrowing.

  3. 03Why does `[1, 2].forEach((n) => out.push(n))` compile, when `forEach` expects a callback returning `void` and `push` returns a number?

    A function type with a `void` return means the caller will ignore the result, not that the function must return nothing. Ignoring a number is harmless, so callbacks returning values are allowed. The stricter rule applies only to a function declaration annotated `: void` directly, which may not return a value.

  4. 04Why is a value of type `any` described as contagious?

    Anything derived from it is also `any`: reading a property, calling it, or passing it through gives back `any`. A single untyped value from `JSON.parse` can turn every variable that touches it into an unchecked one, far from where it started.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark