Assignment Rules: any vs unknown
What You'll Learn
You'll learn the fundamental difference in how TypeScript treats values flowing into and out of any and unknown, which explains why unknown is the safer choice.
The Core Idea
Both any and unknown are top types — meaning you can assign any value to them. But they behave oppositely when you try to assign them to other types:
anyis permissive in both directions: You can assign anything toany, and you can assignanyto anything else. It's the "turn off type checking" escape hatch.unknownis permissive only going in: You can assign anything tounknown, but you cannot assignunknownto other types without narrowing it first.
Think of it like security clearance levels:
anyis like a universal badge that opens all doors and is accepted everywhere — convenient but dangerous.unknownis like a sealed package: you can accept any sealed package, but you must inspect what's inside before using it.
Assignment Rules in Practice
let anyValue: any = "hello";
let unknownValue: unknown = "hello";
// ✅ Both accept any value
anyValue = 42;
unknownValue = 42;
// ✅ any can be assigned anywhere (no safety!)
let str: string = anyValue; // No error, but dangerous
let num: number = anyValue; // No error, but dangerous
// ❌ unknown CANNOT be assigned to other types
let str2: string = unknownValue; // Error!
let num2: number = unknownValue; // Error!
// ✅ unknown requires narrowing first
if (typeof unknownValue === "string") {
let str3: string = unknownValue; // Now OK!
}
The key difference: TypeScript trusts any blindly but forces you to prove what unknown contains before using it.
Why This Matters
The assignment rules are what make unknown genuinely safer than any:
- With
any, a string could flow into a number variable without TypeScript complaining — leading to runtime errors. - With
unknown, you must narrow the type (usingtypeof, type guards, etc.) before TypeScript lets you use the value, catching mistakes at compile time.
Key Takeaway: any disables type checking in both directions, while unknown only disables it going in — forcing you to narrow before the value flows out to other types. This makes unknown the safe alternative when you truly don't know a type yet.