Any, Unknown, Never
Any, Unknown, Never
Section titled βAny, Unknown, NeverβWhat it means
Section titled βWhat it meansβThree special TypeScript types that donβt behave like normal types. any opts a value out of type checking entirely β you can do anything with it, and TypeScript wonβt complain, even if itβs wrong. unknown is the type-safe alternative β it accepts any value, but you must narrow it (check its type) before doing anything with it. never represents a value that canβt exist β the return type of a function that always throws, or an exhaustively-narrowed union with no cases left.
Examples
Section titled βExamplesβlet a: any = "hello";a = 42; // fine, `any` allows anythinga.foo.bar.baz; // no error at compile time -- but crashes at runtime!
let u: unknown = "hello";u = 42; // fine, unknown also accepts anything// u.toUpperCase(); // Error! must narrow firstif (typeof u === "string") { u.toUpperCase(); // fine now -- TypeScript knows `u` is a string here}
function fail(message: string): never { throw new Error(message); // never returns normally}
function assertNever(x: never): never { throw new Error(`Unexpected value: ${x}`); // used for exhaustiveness checks}Common mistake
Section titled βCommon mistakeβReaching for any to silence a type error instead of fixing the underlying type issue β it disables type checking for that value everywhere it flows, defeating the purpose of using TypeScript at all.
function processData(data: any) { // "quick fix" for a type error return data.items.map((i: any) => i.value); // no safety anywhere in this function}
// Better: use `unknown` and narrow, or properly type the datainterface ApiResponse { items: { value: number }[];}function processData(data: ApiResponse) { return data.items.map((i) => i.value); // fully type-checked}Quick practice
Section titled βQuick practiceβ-
Whatβs the key difference between
anyandunknown?Answer
anydisables type checking entirely;unknownalso accepts any value but forces you to narrow its type before you can use it, preserving type safety. -
What does a function returning
nevermean?Answer
The function never returns normally β it always throws an error or enters an infinite loop. -
Why is
unknowngenerally preferred overanywhen a valueβs type isnβt known ahead of time?Answer
unknownkeeps TypeScript's safety checks active β you're forced to verify the type before using the value, catching bugs at compile time thatanywould silently let through.