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

Operations Allowed on any vs unknown

Compare how any permits any operation while unknown prohibits all operations until the type is narrowed.

Operations Allowed on any vs unknown

What you'll learn: How any permits all operations while unknown blocks everything until you narrow the type — understanding why this matters for type safety.

The Fundamental Difference

When you have a value typed as any, TypeScript essentially turns off the compiler for that value. You can call methods, access properties, perform arithmetic — anything goes. TypeScript assumes you know what you're doing and won't stop you.

With unknown, TypeScript takes the opposite approach: it assumes nothing about the value. Until you prove what type it is through narrowing, you cannot perform any operations on it.

What any Allows (Everything)

With any, TypeScript permits:

  • Property access (even non-existent ones)
  • Method calls (even on primitives)
  • Arithmetic operations
  • Function calls
  • Array indexing
  • Anything else you can imagine

TypeScript will not complain, even if the operation would fail at runtime.

What unknown Prohibits (Everything)

With unknown, TypeScript blocks:

  • All property access
  • All method calls
  • All operators except equality checks
  • All function calls
  • Everything until you narrow the type

Why This Design Matters

Think of any as a "trust me" escape hatch that removes all guardrails. Think of unknown as a "prove it first" container that forces you to verify what's inside before using it.

The unknown type gives you the flexibility to accept any value (like any does) but maintains type safety by requiring you to check the type before doing anything with it. This catches errors at compile time instead of waiting for runtime failures.

Key Takeaway: any is permissive and unsafe — it allows all operations without checking. unknown is restrictive and safe — it requires type narrowing before any operation. Always prefer unknown when you need to represent a value of uncertain type.