Course contentsShow
← TypeScript
Lesson 892 of 1,79620. The any Escape HatchFree lesson

Migrating from any to unknown

Apply a strategy to replace any with unknown in existing code and add necessary type guards incrementally.

Migrating from any to unknown

What you'll learn: A practical, incremental strategy for replacing any with unknown in an existing codebase while maintaining type safety.

Why Migrate Step-by-Step?

You can't flip all any types to unknown at once—your code will break everywhere. The solution is tactical replacement: identify one any at a time, replace it with unknown, then add the minimum type guards needed to make that code work again.

Think of it like replacing old electrical wiring in a house. You can't rip out everything at once while people are living there. Instead, you replace one circuit at a time, test it, then move to the next.

The Four-Step Migration Pattern

Step 1: Find Your Target

Start with the any types that are boundaries—function parameters that accept external data, API responses, or parsed JSON. These are high-value targets because they're where untyped data enters your system.

Step 2: Replace with unknown

Change any to unknown. Your code will now have type errors—that's good! These errors show you exactly where you were relying on unsafe assumptions.

Step 3: Add Type Guards Incrementally

For each error, add the narrowing logic that was always needed but hidden by any. Use typeof, in, type predicates, or assertion functions you've already learned.

Step 4: Test and Repeat

Verify the code still works, then move to the next any.

Example Migration Flow

Before:

function processData(data: any) {
  return data.value.toUpperCase();
}

After replacing (breaks):

function processData(data: unknown) {
  return data.value.toUpperCase(); // Error: data is unknown
}

After adding guards (fixed):

function processData(data: unknown) {
  if (typeof data === "object" && data !== null && "value" in data) {
    const obj = data as { value: unknown };
    if (typeof obj.value === "string") {
      return obj.value.toUpperCase();
    }
  }
  throw new Error("Invalid data shape");
}

Migration Priority Order

  1. JSON parsing results – highest risk
  2. API response handlers – external data
  3. Event handlers – user input
  4. Internal function parameters – lower priority
  5. Temporary variables – often can be inferred instead

Key Takeaway: Migrate any to unknown one instance at a time, letting TypeScript's errors guide you to add the type guards that should have existed all along—incrementally improving safety without rewriting everything at once.