unknown vs any: The Key Safety Difference
What you'll learn: How unknown forces you to prove what you have before using it, while any lets you do anything without verification—and why that matters.
The Core Difference
Think of any and unknown like two different ways to handle an unmarked box:
anyis like assuming the box contains exactly what you need and using it immediately—no questions askedunknownis like acknowledging you don't know what's in the box, so you must open it and check before using the contents
How They Actually Behave
With any, TypeScript trusts you completely:
let value: any = "hello";
value.toUpperCase(); // ✓ Allowed
value.nonExistent(); // ✓ Allowed (runtime error!)
value(); // ✓ Allowed (runtime error!)
let num: number = value; // ✓ Allowed
TypeScript performs zero checking. You can call any method, access any property, or assign to any type. It's a complete opt-out.
With unknown, TypeScript requires proof:
let value: unknown = "hello";
value.toUpperCase(); // ✗ Error: Object is of type 'unknown'
value.nonExistent(); // ✗ Error: Object is of type 'unknown'
value(); // ✗ Error: Object is of type 'unknown'
let num: number = value; // ✗ Error: Type 'unknown' not assignable to 'number'
You must narrow the type first:
let value: unknown = "hello";
if (typeof value === "string") {
value.toUpperCase(); // ✓ Now TypeScript knows it's a string
}
Why This Matters
When you receive data you're uncertain about—API responses, user input, parsed JSON—unknown forces you to handle it safely. With any, you're one typo or assumption away from a runtime crash that TypeScript could have prevented.
Key Takeaway: Use unknown when you don't know a type yet—it maintains type safety by requiring explicit narrowing. Reserve any for true escape hatches where you're intentionally bypassing the type system.