What is the difference between unknown and any in TypeScript?
Both can hold any value. any turns off type checking completely, while unknown forces you to check what the value is before you use it, so it is the safe choice.
Explain it simply
Think of any as a sealed parcel you are allowed to use as anything without opening it: TypeScript stops checking, so mistakes slip through. unknown is a sealed parcel you must open and look inside before using it: TypeScript makes you check whether it is a string, a number or an object first. unknown keeps you honest.
Example
function parseJson(text: string): unknown {
return JSON.parse(text);
}
const data = parseJson('{"name":"Asha"}');
// data.name; // Error with unknown: you must check first
if (typeof data === "object" && data !== null && "name" in data) {
console.log((data as { name: string }).name); // safe after the check
}
const risky: any = JSON.parse("42");
risky.toUpperCase(); // compiles, but crashes at runtimeHow it works
anydisables checking for that value and everything it touches, and it spreads: a function returninganymakes callers unsafe too.unknownaccepts any value, but you can only pass it to otherunknownoranyslots until you narrow it withtypeof,instanceof,in,Array.isArrayor a type guard function.
Real-world use
- Values from
JSON.parse,fetchresponses,localStorageandcatch (error)blocks are good candidates forunknown. - Validation libraries (for example zod) take
unknowninput and give you a typed result. anycan be a temporary escape hatch while migrating JavaScript code, but it should be tracked and removed.
Common mistakes
- Using
anyto silence an error instead of fixing the type. - Casting
unknownwithaswithout checking, which is justanyin disguise. - Forgetting that
catch (e)givesunknownwith strict settings; checke instanceof Errorbefore readinge.message.
What to say in the interview
"any switches off type checking, so errors can reach runtime. unknown also accepts any value, but TypeScript forces me to narrow it with checks like typeof or a type guard before I use it. I use unknown for untrusted data such as JSON, API responses and caught errors, and I validate it at the boundary. I treat any as a last resort during migrations."
Follow-up questions
- What is a user-defined type guard?
- What is
neverand how is it different fromunknown? - How does strict mode change the type of a caught error?