When narrowing is lost

Callbacks, mutation, destructuring and object properties: why the checker forgets, and how to keep the narrow type.

More on Unions and narrowing

Keep learning

Overview

chapters · unions and narrowing When narrowing is lost Callbacks, mutation, destructuring and object properties: why the checker forgets, and how to keep the narrow type.

1. The problem: narrowed, then changed behind its back

Narrowing means TypeScript shrinks a type after a check. Example: inside if (x), a string | undefined becomes just string. This chapter is about when that shrunk type is wrong or forgotten. Below, coupon?: means the key is optional (it may be missing, so its value can be undefined). The coupon is checked, then a helper deletes it. TypeScript still believes the check.

How TypeScript gets line 10 wrong

line 1: the declared type line 8: inside if (cart.coupon) line 9: clearExpired(cart) runs line 10: at run time The opposite also happens: the code is safe, but TypeScript forgets the check. Both come from the same rules.

2. The two rules behind every surprise

Function calls: optimistic Callbacks: pessimistic A callback may run later. If the value could change by then, TypeScript forgets the check inside the callback. never changes: narrowing kept everywhere kept in callbacks only if never assigned after (TS 5.4+) anyone could change it: dropped in callbacks

3. Callbacks

order.note is string | undefined. Does line 3 compile? yes, it was checked on line 2 no: 'order.note' is possibly 'undefined' 'order.note' is possibly 'undefined'. Lost: properties are not tracked into callbacks. note: string 'note' is possibly 'undefined'. Lost: the callback might run after line 5. Kept since TS 5.4: nothing assigns to note after the callback (also called a closure) is created.

4. Mutation after narrowing

reads the property again no error, crashes Line 3 reads cart.coupon again after the helper deleted it. TypeScript still trusts the check from line 1. snapshot first safe: coupon is our copy

6. Optional chaining narrows more than you think

inside this if cart is if (cart?.coupon) and cart.coupon is defined if (cart?.coupon !== undefined) undefined cart gives undefined if (cart?.items.length) but length 0 lands in else if (!cart?.coupon) ... else Cart in else the if side is Cart | undefined

7. Evolving let and empty arrays

any means “no type checking at all”. Here it is only a temporary placeholder until TypeScript sees what you put in. any[] (evolving) (string | number)[]

but it cannot evolve across a callback

Variable 'ids' implicitly has type 'any[]' in some locations where its type cannot be determined. Variable 'ids' implicitly has an 'any[]' type. Plain cause: the pushes happen inside a callback, which TypeScript does not follow for evolving types. So it never learns what goes into ids. “Implicitly has an 'any[]' type” means “I couldn't work out a type and gave up” (an error under strict mode).

Remember

Function calls do not undo narrowing, even if they mutate. Property narrowing is dropped inside callbacks. if (a?.b) also proves a exists. Annotate empty arrays that are filled inside callbacks. ! Cheat code → Go deeper: narrowing basics, type predicates, discriminated unions.

More courses

  • Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
  • Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
  • React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
  • Databases in depth — How a query becomes work. Indexes, isolation, locks, and the plans that explain why a page is slow — not an ORM tour.
  • System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
  • NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
  • Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
  • Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
  • AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
  • Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
  • CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
  • Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
  • Docker — What an image is, why layers cache, and how containers find each other on a network.
  • Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
  • Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
  • AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
  • Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.