Hint
any opts out of type checking; unknown is safe any (must narrow); never is the bottom type — unreachable code
These three types occupy opposite ends of the type hierarchy.
any — the escape hatch. Disables all type checking for that value. Assignable to and from everything.
let a: any = 42;
a.foo.bar.baz; // no error — type checking disabled
const b: number = a; // OK — any is assignable to anything
unknown — the type-safe alternative to any. You must narrow it before using it.
let u: unknown = getValueFromAPI();
u.toUpperCase(); // ❌ Error — must narrow first
if (typeof u === 'string') {
u.toUpperCase(); // ✅ Safe — narrowed to string
}
// unknown is NOT assignable to specific types without narrowing
const s: string = u; // ❌ Error
never — the bottom type. A value that can never exist. Used for:
function fail(msg: string): never {
throw new Error(msg); // never returns
}
// Exhaustive check — never signals unhandled case
type Shape = 'circle' | 'square';
function area(s: Shape) {
switch (s) {
case 'circle': return Math.PI;
case 'square': return 1;
default:
const _exhaustive: never = s; // ❌ Error if new case not handled
}
}
unknown over any for values from external sources (API responses, JSON.parse). It forces you to validate before use — the TypeScript equivalent of defensive programming.