Skip to content
typescript questions

TypeScript · 4 of 10junior~1 min

What is the difference between unknown and any?

#types#core

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; // ok

any 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

anyunknown
Assignable to anythingYesNo
Operations without checkYesNo
Type narrowing requiredNoYes
SafetyNoneFull

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 unknown over any whenever possible - it forces you to handle all cases explicitly.

updated

did you know it?

related questions