Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 96 ยท Basic Types

any, unknown, never and void

Learn why any switches off type checking, how unknown keeps untrusted data safe, what never means for exhaustive checks, and how void differs from undefined.

Most types describe a kind of value: string, number[], { id: number }. This lesson is about four special types that describe something else. any and unknown both mean "this could be anything", but they behave in opposite ways. never means "this can't happen". And void means "there's no useful value here".

You'll meet all four constantly: any in old code and careless type definitions, unknown whenever data comes from outside your program (JSON, user input, errors), never in exhaustive switch statements, and void on almost every callback. Understanding them is what separates code that looks typed from code that is safe.

any: the off switch

A value of type any can be used in any way at all. You can call it, read any property from it, pass it anywhere and assign anything to it. TypeScript checks nothing, which means it also catches nothing:

TypeScript any lets bugs through (crashes at runtime on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The program compiles, prints DARK, 16 and undefined, and then crashes with TypeError: Cannot read properties of undefined (reading 'primary'), pointing at line 8. With a real type for settings, TypeScript would have flagged both the typo and the missing colors property before the program ever ran.

any is contagious

The worst thing about any is that it spreads. Anything you read from an any value is also any, and a function that returns it passes the problem on to every caller:

TypeScript
function loadUser(json: string) {
  return JSON.parse(json);       // JSON.parse returns any, so this function does too
}

const user = loadUser('{"name":"Ada"}');   // any
const upper = user.nmae.toUpperCase();     // any, no error, crash at runtime

One any deep in a helper can silently switch off checking across a whole feature.

Where any comes from

You rarely write any on purpose. It sneaks in through:

  • Built-in APIs typed loosely for historical reasons: JSON.parse() returns any, and so does response.json() in the DOM library.
  • Missing annotations. A parameter without a type would be implicitly any, but noImplicitAny (part of --strict) turns that into error TS7006, so you must write a type. See Strict Mode Explained.
  • Libraries with poor type definitions.

Treat any as a last resort for code you're migrating from JavaScript (see Migrating JavaScript to TypeScript), never as a quick fix for an error you don't understand. If you truly don't know a type, use unknown.

unknown: the safe "anything"

unknown also accepts every value. The difference is what you can do with it afterward: nothing, until you prove what it is. You can't read properties, call it or pass it where a specific type is expected:

TypeScript unknown blocks unchecked use (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(3,13): error TS18046: 'data' is of type 'unknown'.
main.ts(4,7): error TS2322: Type 'unknown' is not assignable to type 'number'.
main.ts(5,1): error TS18046: 'data' is of type 'unknown'.

Those errors are the point. unknown forces you to narrow the value with runtime checks. TypeScript follows the checks and gives the value a more precise type inside each branch:

TypeScript Narrowing an unknown value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Each sample prints a matching description, ending with something else: true. Notice the order of checks: typeof null is 'object' in JavaScript, so null must be handled before the typeof value === 'object' branch. Narrowing covers every way to narrow, and Custom Type Guards shows how to validate whole objects.

unknown at the boundaries

The best place for unknown is wherever data enters your program: parsed JSON, messages from other processes, values from localStorage or a form. Accept it as unknown, check it, and return a properly typed value:

TypeScript Validating parsed JSON

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The first call prints { theme: 'dark', fontSize: 14 }. The next three are rejected: [1, 2] gets past the object check (arrays are objects) but has no theme, so it fails the theme check, just like "blue" does; the last one fails the fontSize check. The return statement compiles without any assertion, because by that point TypeScript has narrowed data.theme to 'light' | 'dark' and data.fontSize to number.

Also notice catch (error). In strict mode, a caught value is unknown (the useUnknownInCatchVariables flag), because JavaScript lets you throw anything, not just Error objects. That's why the code checks error instanceof Error before reading .message. Error Handling goes deeper.

Hand-written checks like these get long for big objects; in real projects, schema libraries such as Zod generate them for you, as you'll see in Typing APIs and JSON Data.

any vs unknown at a glance

any unknown
Accepts every value yes yes
Can be assigned to other types yes, to anything only to unknown and any
Read properties, call it yes, unchecked no, narrow first
Safety none full
Use for migration, rare escape hatches untrusted input, generic "anything"

In type-theory terms, both are top types: every type is assignable to them. any is also secretly assignable to everything, which is what makes it unsound.

void: no useful return value

void is the return type of a function that doesn't return a value. TypeScript infers it for functions with no return statement (or only bare return;):

TypeScript void functions and callbacks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This prints [log] starting, undefined and [ 3, 5 ]. The last call is worth understanding. collected.push(...) returns the new array length, a number, yet it's accepted as a (name: string) => void callback. A void return type in a function type means "the caller won't use the result", so returning something is harmless. This rule is what lets you write names.forEach((n) => list.push(n)) without errors. Function Types and Callbacks explains it further.

void vs undefined

At runtime a void function returns undefined, but the types aren't interchangeable:

  • Use void for return types of functions whose result shouldn't be used.
  • Use undefined when undefined is an actual value someone will check, as in string | undefined.

A function declared with return type undefined must return undefined (an implicit end-of-function return is accepted since TypeScript 5.1), and you can't use the result of a void function as if it were a real value: if (logLine('x')) is error TS1345, "An expression of type 'void' cannot be tested for truthiness".

never: values that can't exist

never is the bottom type: the type with no values at all. Nothing (except never itself) can be assigned to it. That sounds useless, but it appears in three important places.

1. Functions that never return

A function that always throws, or loops forever, never finishes normally. Its return type is never, and TypeScript understands that code after a call to it is unreachable:

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

function getPort(raw: string): number {
  const port = Number(raw);
  if (Number.isInteger(port)) {
    return port;
  }
  fail(`Invalid port: ${raw}`);   // TypeScript knows we can't get past here
}

2. Impossible narrowing and exhaustive checks

When narrowing has ruled out every possibility, what's left has type never. You can use that to make TypeScript check that a switch handles every case:

TypeScript Exhaustive switch with never

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

This prints [ '3.14', '9.00', '10.00' ]. In the default branch, all three kinds have been handled, so shape is never and the call to assertNever compiles. The Shape type is a discriminated union, which Union Types introduces and Discriminated Unions explores.

The magic happens when the type grows. Add a triangle to Shape and forget to update area:

TypeScript A forgotten case (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TEXT
main.ts(17,26): error TS2345: Argument of type '{ kind: "triangle"; base: number; height: number; }' is not assignable to parameter of type 'never'.

The error names exactly the case you forgot. In a large codebase this is priceless: change a union in one place, and the compiler lists every switch that needs updating.

3. Types that cancel out

never also shows up when types contradict each other. A value can't be a string and a number at once, so the intersection string & number is never. And when you filter a union down to nothing (for example with Exclude<'a', 'a'>), the result is never. You'll see this a lot in Conditional Types, where never acts like an empty set that disappears from unions: string | never is just string.

TypeScript never in practice

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The output is text number still a string, stop here and 0. An array of never can exist, but it can only ever be empty.

A function expression or arrow function that always throws is inferred as returning never. A function declaration like crash above is inferred as void instead, for backward-compatibility reasons. Write : never explicitly on declarations such as fail() when you want TypeScript to treat calls as dead ends.

The four types side by side

Type Meaning Values Typical use
any "Don't check this" everything migrations, escape hatch (avoid)
unknown "Could be anything, check first" everything JSON, input, caught errors
void "No useful result" undefined (as a return) functions and callbacks
never "Can't happen" none throwing functions, exhaustive checks

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Does this compile? const v: unknown = 5; const n: number = v;

    Every value is assignable TO unknown, but an unknown value can't be assigned to number until a check like typeof v === 'number' narrows it.
  2. 2. What happens when this runs? const x: any = {}; console.log(x.a.b);

    any disables checking, so it compiles. x.a is undefined at runtime, and reading .b from undefined throws a TypeError.
  3. 3. In a switch that handles every member of a union, what is the type of the value in the default branch?

    Narrowing has removed every member, so nothing is left. Passing it to a function that takes never proves the switch is exhaustive.
  4. 4. Is [1, 2].forEach((n) => out.push(n)) (where out: number[]) a type error, given that push returns a number?

    A function type with a void return accepts functions that return anything; the caller just ignores the value.
  5. 5. What is string & number?

    No value can be both a string and a number, so the intersection is the empty type never.

Summary

  • any turns off type checking for a value, and everything derived from it. It hides typos and crashes; avoid it, and watch for loose sources like JSON.parse().
  • unknown accepts any value but lets you do nothing with it until you narrow it with typeof, instanceof, in, Array.isArray() or equality checks. Use it at your program's boundaries; caught errors are unknown in strict mode.
  • void is the return type of functions without a useful result. A void callback type accepts functions that return something, and the result is ignored.
  • never is the type with no values: functions that always throw, impossible branches, contradictory intersections. An assertNever(value: never) helper makes switches exhaustive and points at forgotten cases.
  • any and unknown are top types; never is the bottom type and vanishes from unions.

Next: Union Types