Sub topic 13
A decision guide: any, unknown, or never
This chapter assumes you know the basics of any, unknown, and never from earlier chapters. It also assumes you can write typeof, instanceof, and in checks, and that you can run tsc with strict enabled. Here you will turn that knowledge into a repeatable decision procedure and learn the edge cases that break it.
The three types side by side
Think of types as sets of values. unknown is the set of all values. never is the empty set. any is not a set. It is a switch that turns checking off for whatever it touches.
| Property | `any` | `unknown` | `never` | Column |
|---|---|---|---|---|
| Values it holds | Anything | Anything | Nothing | |
| Assignable to it | Everything | Everything | Only `never` | |
| Assignable from it | To everything except `never` | Only to `unknown` and `any` | To everything | |
| Property access, calls | Allowed without checks | Rejected until narrowed | Not reachable at runtime | |
| In a union (`T \ | X`) | Absorbs everything: `any` | Absorbs everything: `unknown` | Disappears: `T` |
| In an intersection (`T & X`) | `any` | Disappears: `T` | Absorbs everything: `never` |
The table shows two details that matter in practice. any can be assigned to every type except never, so it leaks into any typed variable it touches. unknown cannot leak. It can only flow into unknown or any, or into a type you have proven with a check.
The decision procedure
Ask the questions in this order. Stop at the first one that applies.
Note that any appears only near the end, and the fallback for "I don't know" is unknown. The rest of the chapter explains each branch.
When to choose unknown
Use unknown when a value comes from outside your program's control and you cannot state its type. Typical sources are JSON.parse, fetch responses, localStorage, message events, and catch clauses. The compiler then forces a check before every use. A boundary function should accept unknown, validate it, and return a precise type, so the rest of the code never sees the uncertainty.
interface Config {
host: string;
port: number;
}
function isConfig(value: unknown): value is Config {
return (
typeof value === "object" &&
value !== null &&
"host" in value &&
typeof value.host === "string" &&
"port" in value &&
typeof value.port === "number"
);
}
function loadConfig(text: string): Config {
const data: unknown = JSON.parse(text);
if (!isConfig(data)) {
throw new Error("Invalid config: expected { host: string, port: number }");
}
return data;
}
console.log(loadConfig('{"host":"localhost","port":8080}').port);JSON.parse returns any in the standard library. The line const data: unknown = ... is the containment step: it converts the any into unknown at the first opportunity. The in narrowing used in the guard needs TypeScript 4.9 or later.
Gotchas with unknown
- A type guard is only as honest as its body. The compiler trusts a
value is Configsignature. IfisConfigreturnedtrueunconditionally, the code would still compile. Test guards like any other validation code. - Guards check shape, not meaning. The guard above accepts
port: -5andport: NaN. Add range checks when they matter. - Shallow checks miss nested data. If
Confighad an array of objects, the guard must check each element. For large schemas, a validation library is easier to maintain than hand-written guards. asskips the check.data as Configcompiles with no validation. It is the most common wayunknowngets defeated, because the code looks careful but verifies nothing.
When to choose never
Use never when something cannot happen. It appears in two roles.
As a return type for functions that never return normally, because they always throw or loop forever:
function fail(message: string): never {
throw new Error(message);
}
function getPort(value: string | undefined): string {
if (value === undefined) {
return fail("PORT is required");
}
return value; // narrowed to string
}As a parameter type in an exhaustiveness check. After you handle every member of a union, the leftover type is never, so a function that accepts only never compiles only when nothing was missed:
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number };
function assertNever(x: never): never {
throw new Error(`Unexpected value: ${JSON.stringify(x)}`);
}
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.size ** 2;
default:
return assertNever(shape);
}
}If someone later adds { kind: "triangle"; base: number; height: number } to Shape, the default branch receives a triangle value, which is not never. The call to assertNever stops compiling, and the error points at every switch that needs a new case. The function also throws at runtime, which protects you when data arrives from outside the type system and carries a kind you never declared.
Gotchas with never
- Annotate
never-returning functions explicitly. The compiler uses a call to aneverfunction for control-flow analysis only when the function has an explicit type annotation. A function declaration with: neverworks. Aconst fail = () => { throw new Error() }with no annotation may be inferred as returningvoid, and narrowing after the call is lost. neveris a return type, not a warning. A function that returnsnevermust not reach its end. If it can return, the compiler reports an error, which is the behavior you want.- Empty array literals can become
never[]. In some contexts,const xs = []followed by use leads tonever[]errors such as "Argument of type 'string' is not assignable to parameter of type 'never'". The fix is an annotation:const xs: string[] = []. - A switch without
defaultalso checks. If your function declares a non-voidreturn type and the switch covers every case, the compiler reports "not all code paths return a value" when a case is missing.assertNeveris still preferable, because it also protects at runtime and gives a clear message.
How never behaves inside other types
Because never is the empty set, it vanishes from unions and absorbs intersections. Conditional types use it to delete members from a union.
type Without<T, U> = T extends U ? never : T;
type A = Without<"a" | "b" | "c", "a">; // "b" | "c"
type B = string | never; // string
type C = string & number; // neverThis is useful for decisions too. When a type unexpectedly shows as never, look for an intersection of incompatible types, such as string & number or two object types with the same discriminant property set to different literals. A property that resolves to never often signals a modeling mistake, not a type you wanted.
When any is still the right choice
any remains for a narrow set of cases, and each should be small and commented.
The first case is a generic constraint where unknown would reject valid inputs. Function parameters are checked contravariantly under strictFunctionTypes. A function (a: number, b: number) => number is not assignable to (...args: unknown[]) => unknown, because it cannot accept every unknown. Using any[] in the constraint accepts any function.
// any[] is required here: unknown[] would reject functions with typed parameters.
type AnyFn = (...args: any[]) => unknown;
function logged<F extends AnyFn>(fn: F): (...args: Parameters<F>) => ReturnType<F> {
return (...args) => {
console.log(`calling ${fn.name}`);
return fn(...args) as ReturnType<F>;
};
}
const add = (a: number, b: number): number => a + b;
const loggedAdd = logged(add);
console.log(loggedAdd(1, 2)); // 3, typed as numberThe any never escapes. Callers see Parameters<F> and ReturnType<F>, which are precise types derived from the function they passed in.
The other cases are rarer. They include incremental migration of a large JavaScript codebase, where any marks code you have not yet typed, and workarounds for a defect in a third-party declaration file. In both cases, record why the any exists and aim to remove it.
Worked scenarios
| Situation | Choice | Reason |
|---|---|---|
| Result of `JSON.parse` or `response.json()` | `unknown`, then a guard | The data is external and unverified |
| `catch (err)` variable | `unknown`, then `instanceof Error` | Anything can be thrown |
| Final branch of a `switch` over a discriminated union | `never` via `assertNever` | Catches missing cases at compile time and at runtime |
| Helper that always throws | `never` return type | Enables narrowing after the call |
| Generic wrapper over arbitrary functions | `any[]` in the constraint only | Contravariance rules out `unknown[]` |
| Prototype code you will replace | `unknown` first, `any` only if the compiler blocks you | Cheap to tighten later |
| A value you are too busy to type | `unknown` | `any` hides the problem. `unknown` shows where checks are needed |
Review checklist
- Does each
anyhave a comment explaining whyunknownor a real type will not work? - Does every external input enter as
unknown, and does it pass through a guard or validator before use? - Does every
switchorifchain over a union end inassertNever? - Does every
asassertion follow a check the compiler cannot see, or does it hide a missing check? - Do
never-returning helpers have explicit return annotations?
Exercise
A function parse(text: string) calls JSON.parse(text) and returns the result typed as any. Callers use parse(input).user.name.toUpperCase() without errors. Redesign the signature so that callers must handle bad data, and say which of any, unknown, and never you use and where.
Show answer
Keep JSON.parse returning any internally, but assign it immediately to an unknown variable and validate it with a type guard (such as isUser(value: unknown): value is User). Change parse to return User and throw an error when validation fails, or return User | undefined. unknown is used at the boundary where the untrusted value is held. any appears only in the standard library's JSON.parse signature. never is not needed, except optionally in a helper like fail(message): never that throws on invalid input. Callers now receive a verified User and cannot reach .user.name on unchecked data.
Exercise
You have type Event = { type: "open" } | { type: "close" } and a handle(e: Event) function with a switch that includes assertNever(e) in default. A teammate adds { type: "reset" } to Event. What happens at compile time, and what happens at runtime if the compile error is ignored and a reset event arrives?
Show answer
At compile time, e in the default branch has type { type: "reset" } instead of never, so passing it to assertNever(x: never) is an error, and the error points at handle. At runtime, the default branch calls assertNever, which throws an Error with the message "Unexpected value" and the JSON of the event. The unhandled event fails loudly instead of silently doing nothing.