What is the difference between unknown and any in TypeScript?
The short answer
Both unknown and any can hold a value of any type, but they behave in opposite ways. any turns type checking off for that value, so you can do anything to it and the compiler stays silent. unknown keeps type checking on: it accepts any value, but it will not let you use that value until you narrow it to a specific type. unknown is the safe version of any.
any disables checking
let value: any = getData();value.foo.bar(); // no error, even if it crashes at runtimevalue(); // no errorvalue.toUpperCase(); // no errorEvery line above compiles. If value is actually a number, the code throws at runtime, and TypeScript gave you no warning. any opts that value out of the type system entirely.
unknown forces you to narrow first
let value: unknown = getData();value.foo; // Error: Object is of type 'unknown'value(); // Error: Object is of type 'unknown'To use an unknown value, you have to prove what it is first:
function handle(value: unknown) { if (typeof value === 'string') { console.log(value.toUpperCase()); // safe, narrowed to string }}Where unknown belongs
Use unknown for values that enter your program from outside, where you cannot trust the shape: parsed JSON, a fetch response, or message data:
const data: unknown = JSON.parse(input);if ( typeof data === 'object' && data !== null && 'id' in data) { // safe to read data.id after this check}In modern TypeScript the variable in a catch clause is unknown by default, which forces you to check before using it:
try { doWork();} catch (error) { if (error instanceof Error) { console.log(error.message); }}Interview Tip
Make unknown your default for untrusted input and treat any as a temporary escape hatch you plan to remove. A clean way to say it: any says "trust me, stop checking," while unknown says "I do not know yet, make me prove it." Reaching for unknown signals that you care about keeping the type system intact at the edges of your program.
Why interviewers ask this
This question tests whether you understand the safety model behind TypeScript, not just its syntax. Many bugs come from any quietly spreading through a codebase and removing the checks you were relying on. Knowing that unknown is the safe default for external data, and that it requires narrowing before use, shows real maturity with the language.