any, unknown and never
Overview
Most types describe a set of values: string is all the strings, boolean is true and false. A few special types are about the edges of the type system: a type that matches everything, one that matches nothing, and one that turns checking off. Knowing them — and which to avoid — is essential for writing safe TypeScript.
any: checking switched off
A value of type any can be used as anything, and anything can be assigned to it:
let data: any = JSON.parse('{"port": 8080}');
data.server.port.toFixed(); // no error… crashes at run time
data = 42;
const s: string = data; // no error, though it's a numberany is contagious: everything you read from an any is any too, so one any can quietly disable checking across a whole chain of code.
Where does any come from?
JSON.parse()andresponse.json()returnany;- untyped libraries;
- parameters without annotations when strict mode is off (
noImplicitAny).
It exists for migrating JavaScript and for rare situations where the types really can’t be expressed. In application code, treat every any as a bug waiting to happen.
unknown: the safe alternative
unknown also accepts any value — but it doesn’t let you do anything with it until you’ve checked what it is:
const data: unknown = JSON.parse(text);
data.port;
// error TS18046: 'data' is of type 'unknown'.
if (typeof data === "object" && data !== null && "port" in data) {
console.log(data.port); // ✓ allowed after the checks
}These checks are called narrowing (Type narrowing has the full toolkit):
function describe(value: unknown): string {
if (typeof value === "string") return `text: ${value.toUpperCase()}`;
if (typeof value === "number") return `number: ${value.toFixed(1)}`;
if (Array.isArray(value)) return `array of ${value.length}`;
if (value instanceof Date) return `date: ${value.toISOString()}`;
return "something else";
}Rule of thumb: when a value could be anything — parsed JSON, data from an API, caught exceptions, arguments to a generic logging function — type it unknown, not any. You’ll pay a few ifs, and get code that can’t crash on surprises.
A quick way to type parsed JSON safely:
const config: unknown = JSON.parse(text);(For complex data, a validation library does the checks for you — Validating external data.)
Caught errors are unknown
In JavaScript you can throw anything — strings, numbers, objects. So TypeScript types the variable in catch as unknown (in strict mode):
try {
riskyOperation();
} catch (error) {
// error: unknown
if (error instanceof Error) console.log(error.message);
else console.log(String(error));
}never: the impossible type
never is the type with no values at all. It shows up in two places.
Functions that never return
A function that always throws (or loops forever) never returns a value:
function fail(message: string): never {
throw new Error(message);
}
function getPort(config: { port?: number }): number {
return config.port ?? fail("port is required"); // ✓ never fits anywhere
}Because never has no values, it fits any type — number ?? never is just number.
Impossible branches
When narrowing has removed every possibility, what’s left is never:
function format(value: string | number) {
if (typeof value === "string") return value;
if (typeof value === "number") return value.toFixed(2);
value; // value: never — this line can't be reached
}That’s the basis of exhaustiveness checking, one of TypeScript’s most useful tricks, covered in Discriminated unions.
void
void is the return type of functions that don’t return anything useful:
function log(message: string): void {
console.log(message);
}It differs from undefined in one way: a callback typed to return void may still return a value; the value is just ignored. That’s why [1, 2].forEach((n) => list.push(n)) is fine even though push returns a number.
Summary
| Type | Accepts | Can use without checks? | Use for |
|---|---|---|---|
any |
everything | yes — nothing is checked | avoid; legacy code |
unknown |
everything | no — narrow first | untrusted or unknown data |
never |
nothing | — | functions that throw, impossible cases |
void |
(no useful value) | — | functions that return nothing |
Rule: reach for
unknown, neverany. If you find yourself writingany, ask what you’d check before using the value — then write those checks.
Replace any with unknown
The starter parses settings with any and crashes at run time on bad input. Rewrite it safely: parseJson(text: string): unknown returns the parsed value, or undefined if JSON.parse throws. readPort(value: unknown): number returns value.port only if value is an object (not null) with a numeric port property — otherwise it calls fail("missing port"), a function with return type never that throws an Error. Test it with the three inputs in the starter, catching and printing errors, so the output is 8080, Error: missing port, Error: missing port.
function parseJson(text: string): any {
return JSON.parse(text);
}
function readPort(settings: any): number {
return settings.server.port;
}
for (const text of ['{"port": 8080}', '{"port": "80"}', "not json"]) {
console.log(readPort(parseJson(text)));
}function parseJson(text: string): unknown {
try {
return JSON.parse(text);
} catch {
return undefined;
}
}
function fail(message: string): never {
throw new Error(message);
}
function readPort(value: unknown): number {
if (typeof value === "object" && value !== null && "port" in value && typeof value.port === "number") {
return value.port;
}
return fail("missing port");
}
for (const text of ['{"port": 8080}', '{"port": "80"}', "not json"]) {
try {
console.log(readPort(parseJson(text)));
} catch (error) {
console.log(String(error));
}
}
function unsafe(value: unknown) {
// @ts-expect-error -- unknown can't be used until it's narrowed
return value.port;
}Summary
anyswitches type checking off for a value — anything goes, and errors spread silently. Avoid it.unknownalso accepts any value, but you must narrow it (typeof, instanceof, in) before using it.- Use
unknownfor data you don’t control: JSON, caught errors, user input. neveris the type with no values: functions that always throw, and code paths that can’t happen.voidis the return type of functions that don’t return a useful value.