Interview Q&A / TypeScript

BeginnerIn-depth2 min readUpdated 30 Sept 2026

What is the difference between unknown and any in TypeScript?

SHORT ANSWER

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

ts
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 runtime

How it works

  • any disables checking for that value and everything it touches, and it spreads: a function returning any makes callers unsafe too.
  • unknown accepts any value, but you can only pass it to other unknown or any slots until you narrow it with typeof, instanceof, in, Array.isArray or a type guard function.

Real-world use

  • Values from JSON.parse, fetch responses, localStorage and catch (error) blocks are good candidates for unknown.
  • Validation libraries (for example zod) take unknown input and give you a typed result.
  • any can be a temporary escape hatch while migrating JavaScript code, but it should be tracked and removed.

Common mistakes

  • Using any to silence an error instead of fixing the type.
  • Casting unknown with as without checking, which is just any in disguise.
  • Forgetting that catch (e) gives unknown with strict settings; check e instanceof Error before reading e.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 never and how is it different from unknown?
  • How does strict mode change the type of a caught error?

#types#safety

Related questions

Practise more TypeScript questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open TypeScript quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.