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
