patterntypescriptMajor
TypeScript any vs unknown: use unknown for type-safe handling
Viewed 0 times
TypeScript 3.0+ for unknown
any vs unknowntype safetytype narrowingtype guardunknown type
Error Messages
Problem
Using 'any' disables all type checking — you can call methods, access properties, and pass it anywhere without errors. This defeats the purpose of TypeScript and hides bugs that only appear at runtime.
Solution
Use 'unknown' instead of 'any' for values with uncertain types:
// BAD: any disables type checking
function process(data: any) {
data.foo.bar.baz(); // no error — crashes at runtime
}
// GOOD: unknown requires type narrowing
function process(data: unknown) {
// data.foo; // Error: Object is of type 'unknown'
if (typeof data === 'string') {
data.toUpperCase(); // OK — narrowed to string
}
if (data !== null && typeof data === 'object' && 'foo' in data) {
// narrowed to object with 'foo'
}
}
// With type guards
function isUser(x: unknown): x is User {
return typeof x === 'object' && x !== null && 'id' in x && 'name' in x;
}
// BAD: any disables type checking
function process(data: any) {
data.foo.bar.baz(); // no error — crashes at runtime
}
// GOOD: unknown requires type narrowing
function process(data: unknown) {
// data.foo; // Error: Object is of type 'unknown'
if (typeof data === 'string') {
data.toUpperCase(); // OK — narrowed to string
}
if (data !== null && typeof data === 'object' && 'foo' in data) {
// narrowed to object with 'foo'
}
}
// With type guards
function isUser(x: unknown): x is User {
return typeof x === 'object' && x !== null && 'id' in x && 'name' in x;
}
Why
'any' opts out of the type system entirely — it's assignable to and from everything. 'unknown' is the type-safe counterpart: it accepts any value but forces you to narrow the type before using it. Use 'any' only as a last resort during migration.
Gotchas
- unknown is NOT assignable to other types without narrowing — that's the point
- JSON.parse returns 'any' — consider wrapping with validation (zod, io-ts)
- catch (e) types e as 'unknown' in strict mode — narrow with instanceof Error
Code Snippets
Type-safe error handling with unknown
// Type guard function
function isError(x: unknown): x is Error {
return x instanceof Error;
}
try {
riskyOperation();
} catch (e: unknown) {
if (isError(e)) {
console.error(e.message); // safe
}
}Context
When handling values of uncertain types in TypeScript
Revisions (0)
No revisions yet.