Skip to content
jshacks.dev
TypeScript

any vs unknown vs never

Three special types sit at the edges of TypeScript. Learn what any, unknown and never allow, which errors they raise and when each one is the right choice.

8 min read
Summarize in AI
Flat illustration of two options weighed side by side, with the TypeScript, Vite, npm and JavaScript logos.

Most TypeScript types describe a set of values. string is the set of all strings, and "dark" is a set with one member. Three types do not fit that picture neatly: any, unknown and never. One switches the compiler off, one means "something, but I have not checked what", and one means "nothing, this cannot happen". Teams mix them up constantly, usually by reaching for any when unknown was the honest answer. This post shows what each type permits, the exact compiler messages you will see, and the situations where each is the right tool. It uses TypeScript 6.x with strict enabled, and the official reference is the everyday types page and the narrowing page of the handbook.

any turns the checker off

A value of type any can be assigned to anything, can receive anything, and allows any property access, call or operation. The compiler stops checking that value completely, and the lack of checking spreads to everything computed from it.

any-leak.tsTypeScript
const payload: any = JSON.parse('{"name":"Ada"}');
const nameLength: number = payload.name.length;
console.log(nameLength);
const missing: number = payload.address.length;
console.log(missing);
Text
3
TypeError: Cannot read properties of undefined (reading 'length')

The compiler reports nothing for this file. Line 2 is fine because the JSON does contain a name. Line 4 is just as acceptable to the compiler, yet payload.address is undefined at runtime, so reading .length throws. The variable missing is annotated number, and TypeScript believes it, even though the program never reaches that assignment. That is the danger of any: it does not only hide one mistake, it launders the result into a confident-looking number.

JSON.parse returns any in the standard library for historical reasons, and so does response.json() from fetch. These are the two places where any enters most codebases without anyone typing the word. The first habit to build is to notice when a value arrives as any, and to put a real type on it at the boundary instead of letting it flow inward.

unknown makes you check first

unknown is the safe counterpart. Anything can be assigned to it, just like any, but you cannot do anything with an unknown value until you narrow it.

shout.tsTypeScript
function shout(value: unknown): string {
  return value.toUpperCase();
}
Text
shout.ts(2,10): error TS18046: 'value' is of type 'unknown'.

The error is on the first use of the value, which is where you want it. The compiler refuses the property access because it does not know the value is a string. Assignment to a typed variable is refused for the same reason.

assign-unknown.tsTypeScript
const input: unknown = "12";
const count: number = input;
Text
assign-unknown.ts(2,7): error TS2322: Type 'unknown' is not assignable to type 'number'.

Compare that with the earlier example, where the same assignment from any went through without a comment. The difference in practice is a single keyword, and the difference in outcomes is the line where a bug gets caught.

Narrowing unknown into something useful

You make an unknown value usable by checking it. A typeof test, an instanceof test, an Array.isArray call or a user-defined guard each narrow the type inside the branch where the check passed.

describe.tsTypeScript
function describe(value: unknown): string {
  if (typeof value === "string") return `string of ${value.length}`;
  if (typeof value === "number") return `number ${value.toFixed(1)}`;
  return "something else";
}

console.log(describe("abc"));
console.log(describe(4));
console.log(describe(null));
Text
string of 3
number 4.0
something else

Inside the first if, value is a string, so .length is allowed. Inside the second, it is a number, so .toFixed is allowed. After both checks the compiler still treats value as unknown, and the final return does not touch it. This is the model to prefer for anything that comes from outside the program: parse input as unknown, then check it down to the shape you need. Nothing in the narrowing has to be elaborate. For a larger shape, write a function that returns value is User and check each field once, as shown in the narrowing handbook page.

A useful rule: unknown is for values you receive, and the type you want is for values you hand on. The check is the step in between.

never is the empty set

never is the type with no values at all. Nothing can be assigned to it except another never, and a value of type never can be assigned to anything, since there is no value that could break the assignment. It shows up in three situations.

The first is a function that never returns normally, because it always throws or loops forever.

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

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

console.log(parsePort("8080"));
try {
  parsePort("abc");
} catch (error) {
  console.log(error instanceof Error ? error.message : "unknown error");
}
Text
8080
bad port: abc

Because fail has an explicit never return type on a function declaration, the compiler knows that code after a call to it is unreachable, which is why parsePort can return port as a number without a complaint about NaN flowing through. The explicit annotation matters: the compiler only uses never for control flow analysis when the function's type is written down.

The second situation is a type that has been narrowed until nothing is left. The third is an impossible intersection.

impossible.tsTypeScript
type Impossible = string & number;
const value: Impossible = "a";
Text
impossible.ts(2,7): error TS2322: Type 'string' is not assignable to type 'never'.

A value cannot be both a string and a number, so the intersection collapses to never, and no literal can be assigned to it. When you see an unexpected never in a hover tooltip, look for an intersection of incompatible types or a union that was narrowed too far.

never as an exhaustiveness check

The most practical use of never is making the compiler tell you when you forgot a case. In a switch over a union, the default branch receives whatever the cases did not handle. If you assign that leftover value to a never variable, the code compiles only when nothing is left.

exhaustive.tsTypeScript
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; side: number };
type Triangle = { kind: "triangle"; base: number; height: number };
type Shape = Circle | Square | Triangle;

function area(shape: Shape): number {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.side ** 2;
    default: {
      const unreachable: never = shape;
      return unreachable;
    }
  }
}
Text
exhaustive.ts(13,13): error TS2322: Type 'Triangle' is not assignable to type 'never'.

The Triangle member was added to the union, and nobody wrote its case. The error appears at the default branch and names the exact type that was missed. Add case "triangle" and the error disappears, because the leftover type becomes never. This turns a runtime surprise, a function quietly returning undefined for a new shape, into a compile-time list of places to update. It works best when every consumer of the union has this safety net, so write the helper once if your team uses it often.

At runtime the default branch still exists, so a value that bypassed the types, such as one read from an API, would reach it. For that reason many teams make the helper throw: throw new Error(...) instead of returning the leftover. The check you get from the compiler stays the same, and the runtime path becomes a loud failure instead of a silent one.

Side by side

The three types answer different questions, and the table below summarizes them.

TypeWhat can be assigned to itWhat can be done with itTypical use
anyEverythingEverything, uncheckedMigration code, rare escape hatch
unknownEverythingNothing until narrowedInput from outside the program
neverNothingAssignable to anythingExhaustiveness, functions that throw

If you picture the type system as a hierarchy, unknown is the top, containing every value, and never is the bottom, containing none. any is neither: it is an escape from the hierarchy that behaves as both top and bottom depending on which direction you assign.

Where any is still acceptable

There are honest uses for any. Migrating a large JavaScript file can start by marking the hard parts any and tightening them later. Generic constraints sometimes need any[] for function parameter lists, as in (...args: any[]) => unknown, because a constraint using unknown[] rejects functions with narrower parameters. A test helper that builds deliberately malformed input can use a single as any to bypass the compiler on purpose, and a comment explaining why.

The rules to follow are small. Keep each any local and visible. Do not return it from a function, since the return type spreads the problem to every caller. Do not store it in a shared type. If the project uses ESLint with the typescript-eslint plugin, the no-explicit-any rule and the no-unsafe-* family make accidental any visible in review, and are worth enabling once the codebase is clean enough to adopt them.

Changing a codebase from any to unknown

When you inherit a project full of any, the quickest improvement is at the boundaries. Find every JSON.parse, every response.json() and every catch clause. With strict on, useUnknownInCatchVariables already makes caught errors unknown, which is why the earlier example checked error instanceof Error before reading .message. Replace the others the same way: annotate the result as unknown and write the check that turns it into a real type. The compiler will point at every use that now needs narrowing, which is the list of places that were relying on trust.

Do the work from the outside in. Fixing a type at the edge is cheap, and the fix propagates to everything downstream. Fixing a type in the middle of a call chain while the edge is still any just moves the unsafe step one function over.

Share

Keep reading

Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read
Flat illustration of an editor window full of code, with the TypeScript, Node.js, npm, Vite and JavaScript logos.
TypeScript

What Is TypeScript, and Why Use It?

TypeScript adds static types to JavaScript and checks them before your code runs. Learn what it is, what it catches, what it costs and when to use it.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.