unknown vs any
Both represent "any possible value" but with very different safety guarantees.
any - turns off type checking
ts
let value: any = 'hello';
value.toUpperCase(); // ok
value.nonExistentMethod(); // ok - no error, but crashes at runtime
value = 42; // okany is a complete escape hatch - TypeScript stops checking entirely.
unknown - type-safe alternative
ts
let value: unknown = 'hello';
value.toUpperCase(); // Error - can't use without narrowing
// you must narrow the type first
if (typeof value === 'string') {
value.toUpperCase(); // ok
}Comparison
any | unknown | |
|---|---|---|
| Assignable to anything | Yes | No |
| Operations without check | Yes | No |
| Type narrowing required | No | Yes |
| Safety | None | Full |
When to use
ts
// any - only when migrating JS code or in tests
const legacy: any = getLegacyData();
// unknown - for external data (API, JSON.parse, try/catch)
try {
await riskyOperation();
} catch (error: unknown) {
if (error instanceof Error) {
console.log(error.message);
}
}Prefer
unknownoveranywhenever possible - it forces you to handle all cases explicitly.
updated
did you know it?