Course contentsShow
← TypeScript
Lesson 1676 of 1,79638. Common Patterns and AntipatternsFree lesson

Replacing any with unknown for Safe Migration

Using unknown to stop any creep while forcing explicit type narrowing at usage sites.

Replacing any with unknown for Safe Migration

You'll learn: How to eliminate unsafe any types by replacing them with unknown, forcing explicit type narrowing at every usage site to restore type safety without breaking your code immediately.

The Safe Middle Ground

When you're migrating away from any types in a legacy codebase, flipping straight to strict types can break everything at once. unknown gives you a migration path: it accepts any value (like any), but forces you to prove what you're working with before using it.

Think of any as an unlocked door anyone can walk through, while unknown is a locked door where you must show ID before entering. The door still exists in the same place, but now there's a checkpoint.

The Migration Pattern

Replace any with unknown wherever it appears:

// Before: any allows anything, catches nothing
function processData(input: any) {
  return input.value.toUpperCase(); // No error, crashes at runtime
}

// After: unknown forces explicit checks
function processData(input: unknown) {
  // Error: Object is of type 'unknown'
  // return input.value.toUpperCase();
  
  // Must narrow first
  if (typeof input === "object" && input !== null && "value" in input) {
    const obj = input as { value: unknown };
    if (typeof obj.value === "string") {
      return obj.value.toUpperCase(); // Safe!
    }
  }
  throw new Error("Invalid input");
}

Why This Works for Migration

  1. Non-breaking at call sites: Functions accepting unknown still accept any argument, just like any did
  2. Breaking at usage sites: Forces you to add type guards where the value is actually used
  3. Incremental safety: You can migrate function by function, fixing usage sites one at a time
  4. Compiler-guided: TypeScript errors show you exactly where assumptions were made

Common Replacement Scenarios

External API responses:

// Old
const response: any = await fetch(url).then(r => r.json());
console.log(response.data.user.name);

// New
const response: unknown = await fetch(url).then(r => r.json());
// Compiler forces validation here

Storage and caching:

function getFromCache(key: string): unknown { // was: any
  return JSON.parse(localStorage.getItem(key) ?? "null");
}

// Every caller must now narrow before use
const cached = getFromCache("user");
if (isUserObject(cached)) {
  console.log(cached.name);
}

Key Takeaway: Replacing any with unknown stops type unsafety from spreading through your codebase while giving you concrete compiler errors that guide you to add proper type guards at every actual usage point—making migration incremental and safe.