any vs unknown
The dangerous escape hatch vs the safe mystery box.
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.
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
anydisables the type checker. It is dangerous and should be avoided.unknownrepresents a value whose type is not yet known. It is safe.- You must 'narrow' an
unknownvalue (prove its type) before TypeScript will let you use it.
Done with this concept?
Mark it complete to track your progress. No login needed.