any, unknown, and never
any, unknown, and never
These three special types sit at the extremes of the type system. Understanding when to use each is important for writing correct TypeScript.
any
any opts out of type checking entirely. A value of type any can be assigned to anything and accessed in any way without an error. It is an escape hatch — useful when migrating JavaScript, but overusing it defeats the purpose of TypeScript.
let data: any = fetchRawJson();
data.foo.bar.baz; // no error, but might crash at runtimeunknown
unknown is the type-safe counterpart to any. You can assign anything to an unknown variable, but you cannot use it until you have narrowed its type. Prefer unknown over any when you genuinely do not know the type of a value.
function processInput(value: unknown) {
if (typeof value === "string") {
console.log(value.toUpperCase()); // OK after narrowing
}
console.log(value.toUpperCase()); // Error — value is still unknown here
}never
never represents values that should never occur. A function that always throws or loops forever returns never. It is also the type produced in the impossible branch of an exhaustive switch.
function fail(message: string): never {
throw new Error(message);
}
// Exhaustiveness check with never
type Shape = "circle" | "square";
function area(shape: Shape): number {
switch (shape) {
case "circle": return Math.PI;
case "square": return 1;
default:
const _exhaustive: never = shape;
return _exhaustive;
}
}Avoid any in new code. If you receive any from a third-party library, cast it to unknown immediately and narrow before use.