How would you use TypeScript's 'unknown' type, rather than 'any', when initially typing uncertain data during migration to preserve safety?
Short answer
Type genuinely uncertain values (like a JSON.parse() result or an external API response of unclear shape) as 'unknown' instead of 'any' — this forces you to explicitly narrow or validate the value before using it, catching potential migration mistakes, whereas 'any' silently…
Advertisement
AModel answer
Type genuinely uncertain values (like a JSON.parse() result or an external API response of unclear shape) as 'unknown' instead of 'any' — this forces you to explicitly narrow or validate the value before using it, catching potential migration mistakes, whereas 'any' silently disables all checking and can let bugs slip through unnoticed.
function parseConfig(json: string): unknown {
return JSON.parse(json);
}
const config = parseConfig(rawInput);
// config.someProperty; // Error: 'config' is of type 'unknown' -- must narrow first
if (typeof config === 'object' && config !== null && 'theme' in config) {
console.log((config as { theme: string }).theme); // now safe
}Real-world example
Migrating a data-parsing layer where the exact shape of legacy JSON data isn't fully trusted or known yet.
Likely follow-ups
- Why is defaulting to 'any' during migration considered a common anti-pattern that undermines the whole point of migrating?
Related topics