Sub topic 1
TypeScript `unknown`, `any`, and `never`: The Top and Bottom Types
Prerequisites
This chapter assumes basic TypeScript annotations, interfaces, and union types. You should also know JavaScript typeof, instanceof, and try...catch, and be able to run tsc.
Types as sets of values: top and bottom types
Think of a type as a set of allowed values. A union combines sets. A type at the top accepts every value. A type at the bottom accepts no value.
TypeScript has two edge types:
unknownis the safe top type. Every value can be assigned to it.neveris the bottom type. No value can be assigned to it.
any behaves differently. It can accept and be used as almost anything, so it bypasses the normal set-based checks.
`any`: opting out of type checking
any tells the compiler to trust your operations. Property access, calls, and assignments are allowed even when TypeScript cannot verify them.
let value: any = "hello";
value.toUpperCase();
value = 42;
value.toUpperCase(); // Compiles, but throws at runtimeThis can be useful when gradually migrating untyped JavaScript, but any spreads easily through function results and variables. Treat it as a narrowly contained escape hatch.
`unknown`: the type-safe alternative to `any`
unknown accepts the same inputs without permitting unchecked use. Before reading a property or calling a value, you must narrow it to a more specific type.
let value: unknown = "hello";
if (typeof value === "string") {
console.log(value.toUpperCase());
}The check changes the type inside the if block. This is called narrowing: TypeScript removes impossible types based on runtime evidence.
Narrowing unknown with `typeof`, `instanceof`, and `in`
Use typeof for primitive values and functions. Use instanceof for class instances such as Error. Use in to check whether an object has a property.
function describe(value: unknown): string {
if (typeof value === "string") {
return value.toUpperCase();
}
if (value instanceof Error) {
return value.message;
}
if (typeof value === "object" && value !== null && "name" in value) {
return String(value.name);
}
return "Other value";
}
console.log(describe(new Error("Failed")));The checks do not prove every detail of a complex object. They provide enough evidence for the operation immediately inside the branch.
Exercise
Which type should a function use when it accepts arbitrary external data but must validate it before use?
Show answer
Use unknown, then narrow it with appropriate runtime checks.