Sub topic 13
A Decision Guide: `any`, `unknown`, or `never`
This chapter assumes that you know TypeScript annotations, interfaces, union types, typeof, instanceof, and try/catch. The goal is not to memorize three special types. The goal is to choose the type that accurately describes what your program knows at a particular point.
Start with the question: what values are possible?
TypeScript types can be viewed as sets of possible values.
anypermits almost every operation. It removes most static checking.unknowncan contain any value, but it permits no operation until you check the value.nevercontains no values. It describes impossible states and code paths that cannot finish normally.
Use unknown when a value is real but its shape is not yet known. Use never when a value cannot exist in a correctly working program. Use any only when you deliberately accept the loss of checking.
| Situation | Best choice | Reason |
|---|---|---|
| Data arrives from JSON or an external API | `unknown` | Validate it before use |
| A legacy library has unusable types | Contained `any` | Isolate an unavoidable escape hatch |
| A function always throws or exits | `never` | It does not return a value |
| Every member of a union must be handled | `never` | Detect missing cases |
| A value should not be allowed | `never` | Model an impossible property or branch |
Prefer `unknown` at boundaries
A trust boundary is where data enters your program from a source TypeScript cannot verify, such as a request, file, database, or JavaScript library. Annotate that data as unknown, then narrow it.
interface User {
name: string;
age: number;
}
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
"name" in value &&
typeof value.name === "string" &&
"age" in value &&
typeof value.age === "number"
);
}
function readUser(input: string): User {
const value: unknown = JSON.parse(input);
if (!isUser(value)) {
throw new Error("Invalid user data");
}
return value;
}
console.log(readUser('{"name":"Ada","age":36}').name);The return type value is User makes isUser a user-defined type guard. It tells the compiler what the function proves when it returns true. The checks still run at runtime, so this is safer than merely claiming that the value has a type.
Treat `any` as a contained escape hatch
any is useful when migrating old JavaScript or working around an incomplete library declaration. However, it spreads through expressions. A value derived from any often becomes any too, allowing invalid property access and calls to compile.
Keep the escape hatch at the smallest boundary possible:
function readLegacyName(value: any): string {
if (typeof value?.name !== "string") {
throw new Error("Legacy value has no valid name");
}
return value.name;
}Do not use any merely because narrowing feels inconvenient. A type assertion such as value as User also bypasses validation. Use an assertion only when another checked system guarantees the fact, and keep that assertion close to the guarantee.
Use `never` for impossible outcomes
A never return type means a function cannot complete normally. This fits functions that always throw:
function fail(message: string): never {
throw new Error(message);
}
function requirePort(port: string | undefined): string {
if (port === undefined) {
return fail("PORT is required");
}
return port;
}never also supports exhaustive handling. If a union gains a new member, assertNever makes the missing case a compile-time error.
type Result = { state: "ok"; value: string } | { state: "error"; message: string };
function assertNever(value: never): never {
throw new Error(`Unexpected result: ${JSON.stringify(value)}`);
}
function describe(result: Result): string {
switch (result.state) {
case "ok":
return result.value;
case "error":
return result.message;
default:
return assertNever(result);
}
}How `never` behaves inside types
never disappears from unions because adding no possible values changes nothing:
string | neverbecomesstring.
It dominates impossible intersections:
string & numberbecomesnever.
Conditional types often use it to remove union members:
type Without<T, U> = T extends U ? never : T;
type Letters = Without<"a" | "b" | "c", "a">; // "b" | "c"Exercise
A parser returns data from an untrusted request, and a function handles every member of a union. Which special type should you use in each place?
Show answer
Use unknown for the parser result, then validate and narrow it. Use never in an assertNever helper so the compiler reports any unhandled union member.