Skip to content

Any, Unknown, Never

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.

let a: any = "hello";
a = 42; // fine, `any` allows anything
a.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 first
if (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
}

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 data
interface ApiResponse {
items: { value: number }[];
}
function processData(data: ApiResponse) {
return data.items.map((i) => i.value); // fully type-checked
}
  1. What’s the key difference between any and unknown?

    Answerany disables type checking entirely; unknown also accepts any value but forces you to narrow its type before you can use it, preserving type safety.
  2. What does a function returning never mean?

    AnswerThe function never returns normally β€” it always throws an error or enters an infinite loop.
  3. Why is unknown generally preferred over any when a value’s type isn’t known ahead of time?

    Answerunknown keeps TypeScript's safety checks active β€” you're forced to verify the type before using the value, catching bugs at compile time that any would silently let through.