Course contentsShow
← TypeScript
Lesson 904 of 1,79621. The unknown TypeFree lesson

Assignment Rules: any vs unknown

See how any value can be assigned to unknown, but unknown cannot be assigned to other types without narrowing.

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:

  • any is permissive in both directions: You can assign anything to any, and you can assign any to anything else. It's the "turn off type checking" escape hatch.
  • unknown is permissive only going in: You can assign anything to unknown, but you cannot assign unknown to other types without narrowing it first.

Think of it like security clearance levels:

  • any is like a universal badge that opens all doors and is accepted everywhere — convenient but dangerous.
  • unknown is 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 (using typeof, 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.