Choosing Between any and unknown
What you'll learn: How to decide whether to use any or unknown when dealing with unpredictable data.
The Core Decision
You now know that any disables type-checking completely, while unknown forces you to verify types before use. The question is: when should you choose each one?
Think of it like handling mystery packages:
anyis tearing open the package and using whatever's inside without checkingunknownis opening the package carefully and inspecting the contents first
When to Use unknown
Choose unknown when:
- You're receiving data from external sources (APIs, user input, file parsing)
- You genuinely don't know the shape of the data yet
- You want to maintain type safety while being flexible
function parseJSON(jsonString: string): unknown {
return JSON.parse(jsonString);
// We don't know what structure the JSON contains
}
const data = parseJSON('{"name": "Alice"}');
// Must narrow before use
if (typeof data === 'object' && data !== null && 'name' in data) {
console.log(data.name); // Safe access
}
When to Use any
Choose any only when:
- You're migrating JavaScript to TypeScript gradually
- You're dealing with truly dynamic code that defies typing
- The cost of typing outweighs the benefit (very rare)
any is your emergency escape hatch, not your default choice.
The Rule of Thumb
Default to unknown for type-safe flexibility. Only reach for any when you explicitly want to disable type-checking and accept the risk.
Key Takeaway: Use unknown when you don't know the type but want safety; use any only when you're explicitly opting out of type safety (and ideally, almost never).