any, unknown and never
any switches type checking off, unknown accepts any value but must be narrowed before use, and never is a type with no values. Any infects the code around it, so external data is taken as unknown and narrowed with a guard or a schema. Never underlies exhaustiveness checks: in a default branch the variable is passed to assertNever(x: never), so an unhandled new status breaks the build.
TypeScript · Basics
An API response is parsed as any, the test compiles and fails on undefined. How do we make the compiler help?
An API response is parsed as any, the code has the line data.acount.id with a typo, and the compiler is silent. The test fails at runtime on undefined although the project is TypeScript. There is also the reverse story: a new status REVERSED was added to a switch over a transfer status, while a function that expects "in progress", "done", "failed" quietly returns "failed" for everything unknown. This lesson is about three types that control how much data is trusted: any, unknown and never.
How it works and why. any is a switched-off type check. With an any value you can do anything: access properties, call it as a function, pass it anywhere. Worse, it "infects": the result of anyValue.foo.bar is also any, and distrust of types spreads along the chain. any exists as an escape hatch for migrating from old JS, not as a convenient type.
const data: any = await res.json();
const id = data.acount.id;
console.log(id.toUpperCase());
This fragment compiles fully. The typo acount turns into undefined, and the next line fails with an error about calling a method on undefined, far from the real cause. unknown is the safe version: you can put anything into the variable, but cannot use it before checking. The compiler demands narrowing: typeof, instanceof, in, a custom type guard or a schema.
In strict mode (strict, precisely useUnknownInCatchVariables) the variable in catch is also unknown: anything can be thrown, not only an Error.
try {
await doWork();
} catch (e) {
// e is unknown under "strict"
const msg = e instanceof Error ? e.message : String(e);
console.error(msg);
}
never is a type with no values. It is returned by a function that always throws or never finishes. It is also the "bottom" of the hierarchy: a value of type never can be assigned anywhere, while only never can be assigned to never. Exhaustive checking rests on this: in the default branch the variable has type never only if every variant of the union has already been handled.
Types from top to bottom
Example: the code compiles and a bug hides. A test helper returns the expected badge of a transfer status:
type Status = 'PENDING' | 'COMPLETED' | 'FAILED';
function expectedBadge(s: Status): string {
switch (s) {
case 'PENDING':
return 'In progress';
case 'COMPLETED':
return 'Done';
default:
return 'Failed';
}
}
While there are three statuses everything works. When the backend adds REVERSED and the Status type is updated, the function keeps compiling: the default branch quietly returns "Failed" for a reversed transfer. A test with it either passes wrongly or fails with a mismatch whose trail leads the wrong way. This scenario is dangerous precisely because nothing turns red.
The fix is to make default the "this cannot happen" branch and leave it to the compiler:
type Status = 'PENDING' | 'COMPLETED' | 'FAILED' | 'REVERSED';
function assertNever(x: never): never {
throw new Error('Unhandled status: ' + String(x));
}
function expectedBadge(s: Status): string {
switch (s) {
case 'PENDING':
return 'In progress';
case 'COMPLETED':
return 'Done';
case 'FAILED':
return 'Failed';
case 'REVERSED':
return 'Reversed';
default:
return assertNever(s);
}
}
If another variant appears in Status and no branch is added for it, assertNever(s) receives a value that is not never, and the compiler reports something like "Argument of type '"ARCHIVED"' is not assignable to parameter of type 'never'". The code stops building until the status is handled. There is a second protection, at runtime: if the server returns a value that is not in the type, assertNever throws a clear error instead of a quiet wrong result.
What default does in a switch
default: return 'Failed'
A new status lands in someone else value. The build is green, the error is visible only by chance.
default: assertNever(s)
A new status breaks the build, and an unknown value from the server gives a clear runtime error.
Limits and alternatives. An exhaustive check works only when the Status type agrees with the real API: a union written by hand can lag behind. For data from the outside world unknown is only the beginning; a real check (a guard or a schema such as zod) is needed next. as narrows a type without checking, so (x as Foo) brings back the same danger as any, only locally. To enforce discipline in the project, turn on the ESLint rule @typescript-eslint/no-explicit-any, and the type-checked rule set adds a ban on unsafe operations with any values (no-unsafe-*). An alternative to an exhaustiveness check through never is satisfies or a Record<Status, string> object where the compiler requires all keys.
Common mistakes.
const data: any = await res.json(): the check is off and typos in fields show up at runtime. Preferunknownand narrowing.as Fooon external data: the sameany, only looking like a check.- A
defaultwith a "smart" value in aswitchover a union: a new status slips through unnoticed. catch (e)readinge.messagewithout a check: in strict modeeisunknown.- Confusing
neverwithvoid: avoidfunction finishes and returns nothing, while aneverfunction never returns.
Check yourself
After adding REVERSED to Status the project builds without errors, although the function has default: return 'Failed'. Why, and what changes so that the build fails?
Answer
The default branch has no exhaustiveness check, so any unknown status simply lands in "Failed". The default must pass the variable to a function that accepts never (assertNever(s)): then unfinished handling becomes a compile error.
The code catch (e) { console.log(e.message) } gets an error under strict. Why, and how is it fixed?
Answer
Under strict the variable in catch has type unknown, because anything can be thrown. Narrow it: e instanceof Error ? e.message : String(e).
any turns type checking off, while unknown is safer: it must be narrowed before use. never is a type with no values, used in an exhaustive switch. Middle/Senior: For external data I take unknown and narrow it with a guard or a schema, and I ban any with an ESLint rule. In a switch over statuses, default calls assertNever: a new status breaks the build, and an unknown value from the server gives a clear runtime error.