What is the difference between any, unknown and never in TypeScript?
Quick answer
any turns off checking. unknown is a type-safe any: you must narrow it before use. never means a value cannot exist, used for exhaustive checks and functions that always throw.
A value typed any can be passed anywhere and you can read any property on it, so a typo compiles. unknown is what you give to untrusted input (JSON.parse, a network payload) until you prove its shape with typeof, in, or a type guard.
never is the empty set. A function with return type never does not return (throw or infinite loop). In a switch, assigning the leftover value to const _exhaustive: never = value makes the compiler fail when a new union member is added and not handled.
function handle(x: unknown) {
if (typeof x === "string") return x.toUpperCase();
throw new Error("expected string");
}
function fail(message: string): never {
throw new Error(message);
}