gyanguide interview materials
typeScript

What is difference between unknown & Any data type in TypeScript

Here is the difference between them:

Featureanyunknown
Type safety❌ No safety✅ Safe
Can access properties directly?✅ Yes❌ No
Can call functions directly?✅ Yes❌ No
Need type checking before use?❌ No✅ Yes
Best useWhen you don’t care about type checkingWhen type is unknown but safety is important

any Example

let value: any = "Raj";

value.toUpperCase(); // ✅ Works
value(); // ✅ No TypeScript error
value.xyz; // ✅ No error

Problem with any:
TypeScript stops checking errors.

let value: any = 10;
value.toUpperCase(); // Runtime error

unknown Example

let value: unknown = "Raj";

value.toUpperCase(); // ❌ Error

You must check the type first:

let value: unknown = "Raj";

if (typeof value === "string") {
console.log(value.toUpperCase()); // ✅ Safe
}

Real-world Scenario

any

Use when:

  • Migrating old JavaScript code
  • Quick prototyping
  • You intentionally want to skip checking

unknown

Use when:

  • API response type is not known
  • User input can be anything
  • Safer coding is needed

Example:

function handleApi(data: unknown) {
if (Array.isArray(data)) {
console.log(data.length);
}
}

Easy Memory Trick

  • any = “Do anything”
  • unknown = “I don’t know yet, check first”

Interview One-Line Answer

any disables TypeScript type checking, while unknown is a safer type that requires type checking before usage.