TypeScript Type Guards: "x is T" and Assertion Functions

Write your own type guard with "value is T" and assertion functions with "asserts value is T", and see how a wrong predicate lies to the checker.

In this chapter

Type predicates and assertion functions

More on Unions and narrowing

Keep learning

Overview

chapters · unions and narrowing Type predicates and assertion functions Teach the checker your own test with “x is T” and “asserts x is T”, and where they can lie.

1. The problem: move a check into a helper, lose the narrowing

returns boolean Property 'paidAt' does not exist on type 'Order'. Property 'paidAt' does not exist on type 'PendingOrder'. returns a type predicate order: PaidOrder

2. The parts of x is T

Return type slot written where boolean would go Names a parameter o is PaidOrder: o must be a parameter name Returns a boolean at runtime it is still just true or false

order after calling isPaid(order)

before the call PaidOrder | PendingOrder inside if (isPaid(order)) inside the else

3. filter: the most common predicate

What is the type of codes? (string | undefined)[] Since TS 5.5, simple arrow functions get an inferred predicate: TypeScript works out x is T for you, without you writing it. x !== undefined No inferred predicate. c is string would also promise "when false, c is not a string". But !!'' is false, and '' is a string. That promise would break, so TypeScript infers nothing.

The type of promo, line by line

line 7: assertIsString throws unless it is a string line 8: we got here, so it did not throw Two forms. asserts v is T narrows v. asserts cond narrows whatever the condition proves.

asserts condition, like Node's assert()

cart: Cart Line 6 throws if cart is falsy (here: null). So on line 7, null is ruled out and cart is Cart.

the arrow-function gotcha

Assertions require every name in the call target to be declared with an explicit type annotation.

compiles, crashes

input: number (it is a string) A subtler lie: the predicate checks more than its type says. The false branch is then wrong. Below, a paid order of $20 returns false. TypeScript then removes PaidOrder and calls it a PendingOrder, but it is really paid. order: PendingOrder (wrong!) Predicate claims more than it checks True branch trusts a type that was never checked. Crash later, far away. Predicate checks exactly its type True means T, false means not T. Extra conditions go outside: isPaid(o) && o.total > 100.

6. Which tool when

narrows in if narrows after call checked by TS use for inline check inferred predicate (5.5+) filter, small helpers reusable guards validate input, then go

Remember

A helper returning boolean does not narrow anything. x is T narrows in the true branch and removes T in the false one. asserts functions throw or narrow everything after the call. Predicates are trusted, not checked. Keep the body exactly matching the claim. ! Cheat code → Go deeper: built-in narrowing checks, discriminated unions, when narrowing is lost.

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.