TypeScript FoundationsLesson 1.5
TypeScript any, unknown, and never types when to use each
any type risks, unknown type safe alternative, never type unreachable code, type narrowing with unknown, exhaustive checks with never
any — escape hatch, use sparingly
any turns off all type checking for a variable. Avoid it — it defeats the purpose of TypeScript:
let val: any = "hello";
val = 42; // fine
val.toUpperCase(); // no error — but crashes if val is 42unknown — safe alternative to any
unknown accepts any value but forces you to check the type before using it:
function process(input: unknown) {
if (typeof input === "string") {
console.log(input.toUpperCase()); // safe
}
// input.toUpperCase() here would be a compile error
}Use unknown for values from external sources: API responses, parsed JSON, user input.
never — code that should not be reached
never represents a value that can never exist. TypeScript assigns it to unreachable code paths:
function fail(msg: string): never {
throw new Error(msg);
}
function assertExhaustive(x: never): never {
throw new Error("Unhandled case: " + x);
}The exhaustive check pattern is powerful with discriminated unions — if you add a new variant and forget to handle it, TypeScript flags the never assignment as an error before runtime.
