liveBook · Manning

Type predicate

As explained in Essential TypeScript 5, Third Edition

A type predicate is a TypeScript function-result annotation that identifies a parameter and asserts the type it has when the result is true.

A type predicate is a function-result annotation that identifies the tested parameter and the type it has when the function returns true. The syntax uses `parameter is Type`, allowing TypeScript to narrow an object inside a conditional. section 10.2.6

Guarding people and products

type Product = { id: number; name: string; price?: number }; type Person = { id: string; name: string; city: string }; function isPerson(testObj: any): testObj is Person { return testObj.city !== undefined; } dataItems.forEach(item => { if (isPerson(item)) { console.log(`Person: ${item.name}: ${item.city}`); } else { console.log(`Product: ${item.name}: ${item.price}`); } }); When `isPerson(item)` is true, the compiler treats `item` as `Person`; otherwise, the remaining branch is handled as `Product`. section 10.2.6

Keep these constraints in mind:

  • Reuse a named guard instead of repeating `in` checks, but design the test carefully: optional properties can make shapes overlap. section 10.2.6
  • Prefer the convention `is` followed by the guarded type, such as `isPerson` or `isProduct`. section 10.2.6

How Essential TypeScript 5, Third Edition covers it

How deep it goes
Explains predicate syntax, compiler narrowing, implementation, naming, and overlapping-shape limitations.
Examples
Demonstrates `Product` and `Person` objects classified by an `isPerson` function.
What it assumes
Assumes familiarity with TypeScript object types, properties, functions, and conditional branches.
What you can do after
Apply it via TypeScript to narrow objects and safely access properties specific to each type.
How it connects
Connects type guards with object types, union types, optional properties, and the `in` keyword.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Essential TypeScript 5, Third Edition. The section links point to the parts of the book it draws on.