any vs unknown

⭐ Interview Importance: HIGH
⏱️ Revision Time: 3 min

TL;DR

Both any and unknown can hold any value.
However, any completely turns off the type checker (dangerous), while unknown forces you to perform a type check before you can perform operations on the value (safe).

Mental Model

How It Works

any

When a value is any, TypeScript trusts you implicitly. You can call any method, access any property, or pass it to any function. It is effectively writing vanilla JavaScript.

unknown

When a value is unknown, TypeScript says: “I don’t know what this is, so I won’t let you do anything with it until you prove what it is.” You must use Type Narrowing (like typeof checks) to use the value.

Example

// --- ANY (Dangerous) ---
let dataAny: any = 10;
dataAny.toLowerCase(); // Compiles fine, but crashes at runtime!


// --- UNKNOWN (Safe) ---
let dataUnknown: unknown = "hello";

// dataUnknown.toLowerCase(); // TS ERROR: Object is of type 'unknown'

// You MUST narrow the type first:
if (typeof dataUnknown === "string") {
    // Inside this block, TS knows dataUnknown is a string
    console.log(dataUnknown.toLowerCase()); 
}

Common Interview Questions

When should you use any?

Almost never in modern TypeScript codebases. The only acceptable use cases are migrating a legacy JavaScript codebase to TS incrementally, or dealing with an incredibly complex third-party library whose types are completely broken.

When should you use unknown?

Use unknown whenever you are accepting dynamic data where you don’t know the shape upfront. Common examples include parsing JSON from an HTTP request (JSON.parse returns any by default, but it’s safer to cast it to unknown), or catching errors in a try/catch block (catch (error: unknown)).