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

Localized any with Strict Boundaries

When any is necessary, containing it to small scopes with well-typed wrapper functions.

Localized any with Strict Boundaries

You'll learn how to contain the any type to the smallest possible scope using wrapper functions that expose safe, well-typed interfaces.

The Containment Strategy

Sometimes any is genuinely unavoidable—perhaps you're working with a truly dynamic API or a third-party library that defies typing. The key is not letting any spread through your codebase like a virus.

Think of any like radioactive material: you need containment vessels. The strategy is to quarantine any inside small, carefully designed functions that:

  1. Accept any internally (where you must)
  2. Perform whatever dynamic operations are needed
  3. Return a properly typed result

The rest of your codebase never sees the any—only the safe types coming out.

The Pattern

// ❌ BAD: any leaks everywhere
function processData(data: any) {
  return data.results.map((item: any) => item.value);
}

const results = processData(response); // results is any!


// ✅ GOOD: any contained, typed interface exposed
function processData(data: any): string[] {
  // any confined to this function body
  return data.results.map((item: any) => item.value);
}

const results = processData(response); // results is string[]

Notice the explicit return type annotation string[]. This is your boundary—the wall that prevents any from escaping.

The Wrapper Function Technique

// Wrapper function with strict boundary
function parseUnknownJSON(jsonString: string): { name: string; age: number } {
  const parsed: any = JSON.parse(jsonString); // any stays here
  
  return {
    name: parsed.name,
    age: parsed.age
  }; // typed object leaves
}

const user = parseUnknownJSON('{"name":"Alice","age":30}');
// user is { name: string; age: number } — safe!

The any never leaves the parseUnknownJSON function. Your entire application works with clean, typed data.

Why This Works

By providing explicit return types on your wrapper functions, you force TypeScript to verify that the boundary is maintained. If you accidentally return the raw any, TypeScript will still accept it—but the caller receives the safe type you promised.

The pattern creates a firewall: dynamic chaos inside, type safety outside.

Key Takeaway: When any is necessary, isolate it within small functions with explicit, well-typed return types. Never let any cross function boundaries into the rest of your codebase.