Refactoring any to unknown
You'll learn: How to safely replace any with unknown in existing code to improve type safety without breaking functionality.
When you inherit code littered with any, or realize you've been too liberal with it yourself, the path to better type safety doesn't require a complete rewrite. Refactoring any to unknown is a strategic, incremental upgrade that forces explicit type checking exactly where it matters.
The Refactoring Strategy
Start by identifying any usage in your codebase. Replace it with unknown one location at a time. TypeScript will immediately show you every place where you were making unsafe assumptions about the value's type. These compiler errors are your roadmap—they reveal where type guards or assertions were missing all along.
The beauty of this approach is that it's mechanical and safe. You're not guessing what the type should be; you're making explicit what your code already assumes implicitly.
Step-by-Step Process
Before:
function processUserData(data: any) {
console.log(data.name.toUpperCase());
return data.age * 2;
}
After refactoring to unknown:
function processUserData(data: unknown) {
// TypeScript now forces you to prove what data is
if (typeof data === 'object' && data !== null &&
'name' in data && 'age' in data) {
const user = data as { name: string; age: number };
console.log(user.name.toUpperCase());
return user.age * 2;
}
throw new Error('Invalid user data');
}
Notice how the refactor surfaces the hidden assumptions: you always expected data to have name and age properties, but any let you pretend that was guaranteed.
Key Takeaway: Refactoring any to unknown is like adding guardrails to a bridge that was always dangerous—it doesn't change what the code does, but it forces you to acknowledge and handle the risks that were always there.