Course contentsShow
← TypeScript
Lesson 923 of 1,79621. The unknown TypeFree lesson

When to Stop Narrowing

Recognizing when you've narrowed enough versus over-engineering nested type guards.

When to Stop Narrowing

What you'll learn: How to recognize when you've narrowed an unknown value sufficiently versus when you're adding unnecessary complexity with excessive type guards.

The Narrowing Sweet Spot

When working with unknown values, there's a balance between safety and practicality. You could theoretically narrow forever, checking every possible property and edge case, but at some point you've verified enough to safely proceed.

Think of narrowing like checking ingredients before cooking. If you're making pasta, you verify you have noodles, sauce, and water. You could also check the expiration date on the salt, measure the exact pH of your water, and verify the molecular structure of your tomatoes — but you'd never start cooking.

The Key Questions

Have you eliminated the dangerous cases?
Once you've ruled out null, undefined, and confirmed the basic shape you need, you've often done enough. If you need an object with a name property, checking that it's an object and has name is usually sufficient:

function processEntity(data: unknown) {
  // Essential narrowing
  if (typeof data !== "object" || data === null) {
    throw new Error("Invalid data");
  }
  
  if (!("name" in data)) {
    throw new Error("Missing name");
  }
  
  // This is enough - you can work with data.name now
  console.log(data.name);
  
  // Overkill: checking every theoretical property
  // if (typeof data.name !== "string") { ... }
  // if (data.name.length > 0) { ... }
  // if (/^[A-Z]/.test(data.name)) { ... }
}

Can runtime still surprise you?
After narrowing, TypeScript trusts you, but runtime doesn't. If data.name could actually be a number or empty string, and that breaks your logic, narrow further. Otherwise, stop.

Is the additional check preventing real bugs?
Narrow when it prevents actual errors in your domain. Don't narrow just because you theoretically could. If you're parsing API responses and the API always sends strings for certain fields, one typeof check on the parent object might be all you need.

Over-Narrowing Red Flags

  • Deep nesting of type guards (more than 2-3 levels)
  • Checking properties you never actually use
  • Validating format details TypeScript can't enforce anyway (like email regex patterns)
  • Creating type predicates for one-time use cases

Key takeaway: Narrow until you've eliminated the runtime errors you actually care about, then trust your narrowed type and move on. Perfect type safety is an illusion — stop when you've achieved practical safety.