Here is the difference between them:
| Feature | any | unknown |
|---|---|---|
| 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 use | When you don’t care about type checking | When 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
anydisables TypeScript type checking, whileunknownis a safer type that requires type checking before usage.