any vs unknown
any turns the type checker off for a value. unknown means "a value is here, but you may not use it until you narrow it." Prefer unknown whenever you do not yet know the type.
Detailed Explanation
Both any and unknown accept every value. That is the only thing they share. The difference is what you are allowed to do with the value afterwards.
any is assignable to every type, and every operation on an any is allowed. Reading .foo, calling it as a function, adding it to a number — the compiler stays silent. The type of any expression derived from any is also any, so the looseness spreads. One any at the edge of a module can infect a whole call graph.
unknown is the type-safe counterpart. You can assign anything to an unknown variable. You cannot assign an unknown to a more specific type, and you cannot read properties or call it, until you narrow. Narrowing is ordinary JavaScript: typeof, instanceof, in, Array.isArray, a user-defined type guard, or a validator that returns a typed result.
This pair is how TypeScript models the boundary between your program and the rest of the world. JSON.parse returns any for historical reasons. fetch().then(r => r.json()) returns any. A catch clause under useUnknownInCatchVariables is unknown. The honest type for "I have not inspected this yet" is unknown. The honest type for "I have given up" is any.
noImplicitAny does not ban any. It bans values whose type the compiler could not infer and therefore silently made any. Writing : any on purpose still compiles. That is why a codebase can have noImplicitAny on and still be full of holes: every explicit any, and every as any, is a hole you opted into.
When do you still write any? Three cases, and they should be rare. Escaping a compiler bug or a mis-typed third-party declaration, for a few lines, with a comment. Migrating a JavaScript file where annotating everything at once is not feasible. And generic constraints that truly need to accept every value and let the caller use it freely — which is almost never, because a generic T already does that without giving up checking.
unknown costs a few extra narrowing lines. Those lines are the ones that would have been production incidents. any costs nothing to write and a great deal to debug, because the failure happens at runtime, far from the annotation that caused it.
Code Examples
1. The same incoming value, two types, two outcomes.
// 1. The same incoming value, two types, two outcomes.
function handleAny(value: any) {
value.toUpperCase(); // compiles; throws if value is not a string
const n: number = value; // compiles; n may not be a number
}
function handleUnknown(value: unknown) {
// value.toUpperCase();
// Error: Object is of type 'unknown'.
if (typeof value === "string") {
value.toUpperCase(); // narrowed to string
}
}2. JSON.parse is any; wrap it so the hole does not spread.
// 2. JSON.parse is any; wrap it so the hole does not spread.
function parseObject(text: string): unknown {
return JSON.parse(text);
}
const raw = parseObject('{"id":1}');
// raw.id
// Error: Object is of type 'unknown'.
if (raw !== null && typeof raw === "object" && "id" in raw) {
const id = (raw as { id: unknown }).id;
if (typeof id === "number") {
console.log(id.toFixed(0));
}
}3. Catch variables are unknown under strict.
// 3. Catch variables are unknown under strict.
try {
throw new Error("disk full");
} catch (err) {
// err.message
// Error: 'err' is of type 'unknown'.
if (err instanceof Error) {
console.log(err.message); // "disk full"
}
}Common Gotchas
`any` is contagious
a function that returns `any` makes every caller `any` too. Once it is in a return type, annotations downstream cannot recover the lost information unless they re-assert.
`unknown` is not a runtime check
assigning to `unknown` does not validate anything. You still need `typeof`, a type guard, or a schema library before you treat the value as a specific shape.
`unknown` is the top type; `never` is the bottom
every type is assignable to `unknown`, and `never` is assignable to every type. They are opposites, not cousins of `any`.
`as any` hides the error instead of fixing it
if a value does not match a type, the cast will compile and the next read will throw. Narrow or fix the source type.