TypeScript · Types that pay for themselves
What is the difference between unknown and any?
Short answer
any disables type checking and spreads unsafely. unknown accepts any value but requires narrowing before use, which makes it the right type for untrusted input.
Both any and unknown can hold any value. The difference is what the compiler lets you do with it. any is assignable to everything and allows every operation, so errors propagate silently. unknown is assignable to almost nothing until you prove its shape with a check.
function parse(input: unknown): string {
if (typeof input === "string") {
return input.trim();
}
throw new Error("Expected a string");
}
const value: any = "text";
value.thisDoesNotExist();Why unknown is safer
- unknown forces a runtime check before property access or calls
- any disables checking for the value and for everything derived from it
- unknown is appropriate for JSON, network responses and user input
- any is sometimes necessary at a library boundary, but it should be contained
- Prefer a validated concrete type over either one in application code
The danger of any is contagion. Once a value is any, properties read from it are any, function results are any, and errors disappear from the type checker. unknown stops that spread because every use requires narrowing first.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why is any assignable to every type?
- 2What must you do before using an unknown value?
- 3When is any acceptable?
- 4How does any affect values derived from it?
Say it in the interview
any turns off checking and spreads to everything it touches. unknown accepts any value but forces me to narrow before I use it, so it is the right type for data from JSON, APIs or user input. I use unknown at boundaries and narrow into a concrete type. If I see any in a codebase, I treat it as a place where a runtime bug can hide.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live TypeScript mock interview and get scored feedback on depth, clarity and confidence.