any vs unknown

The dangerous escape hatch vs the safe mystery box.

TypeScript4 min readConcept 2 of 54

The Escape Hatch and the Mystery Box

Sometimes you don't know what type a value will be—perhaps it's coming from a third-party API or user input. TypeScript gives you two options: any and unknown.

any is an escape hatch. It completely disables the type checker for that variable. You can do literally anything with it, just like plain JavaScript.

unknown is a mystery box. It tells the compiler "I don't know what this is yet." Unlike any, TypeScript will block you from doing anything with an unknown value until you perform a check to prove what it actually is.

Why prefer unknown over any?

Using any brings back all the runtime crashes that TypeScript was designed to prevent. If you type a variable as any, TypeScript will let you call .toUpperCase() on it, even if it turns out to be a number at runtime. The app will crash.

Using unknown forces you to be safe. TypeScript will throw a red squiggle if you try to call .toUpperCase() on an unknown value. You must first write an if (typeof val === 'string') check before the compiler allows the method call.

Narrowing the unknown

To use an unknown value safely, you must 'narrow' its type. This is typically done using the typeof operator or type predicates.

typescript let input: unknown = getNetworkData(); // Error: Object is of type 'unknown'. input.toUpperCase(); if (typeof input === 'string') { // Safe! TypeScript now knows input is a string here. input.toUpperCase(); }

Try it

Toggle between any and unknown to see how the compiler reacts to a risky method call.

// We fetch data, but it turns out to be a number
let input: unknown = 42;

// Try to call a string method
input.toUpperCase();

Compile Error

Object is of type 'unknown'

TypeScript blocked the build. The broken code never reaches the browser.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What happens when you try to access a property on an 'unknown' variable without checking its type first?

Remember this

  • any disables the type checker. It is dangerous and should be avoided.
  • unknown represents a value whose type is not yet known. It is safe.
  • You must 'narrow' an unknown value (prove its type) before TypeScript will let you use it.

Done with this concept?

Mark it complete to track your progress. No login needed.