Course contentsShow
← TypeScript
Lesson 130 of 1,7963. Basic TypesFree lesson

Assigning to unknown

Learn that any value can be assigned to unknown, making it useful for unpredictable inputs.

Assigning to unknown

You'll learn that unknown accepts any value, making it the safe way to receive unpredictable data.

The Core Idea

While any is dangerous because it lets you do anything with a value, unknown is its cautious sibling. The key difference starts with assignment: you can assign any value to unknown, just like any. This makes unknown perfect for situations where you genuinely don't know what type is coming your way—user input, API responses, or third-party libraries.

Think of unknown like a locked box. You can put anything inside (assign any value), but you can't use what's inside until you verify what it is. With any, the box is always open—convenient but risky.

Assignment Examples

let mystery: unknown;

mystery = 42;           // ✓ number → unknown
mystery = "hello";      // ✓ string → unknown
mystery = true;         // ✓ boolean → unknown
mystery = null;         // ✓ null → unknown
mystery = undefined;    // ✓ undefined → unknown
mystery = [1, 2, 3];    // ✓ array → unknown

Every one of these assignments is valid. unknown acts as a universal container—it holds anything without complaint.

Why This Matters

When dealing with unpredictable inputs (like data from JSON.parse() or user uploads), you need a type that says "I'll accept this, but I'm not making assumptions about what it is." That's unknown. Unlike any, which pretends to know everything, unknown honestly admits uncertainty.

Key Takeaway: Any value in TypeScript can be assigned to unknown, making it the safe choice for truly unpredictable data before you narrow it down to something specific.