TypeScript 7 reference · Type Operators and Keywords

TypeScript type predicates (x is T) Keyword

A function returning 'value is Type' tells TypeScript that the value has that type wherever the function returns true.

TypeScript 7 Since 1.6

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

function f(x: unknown): x is T

Examples

Narrow a unionTry it yourself
interface Cat { meow(): string }
interface Dog { bark(): string }
function isCat(pet: Cat | Dog): pet is Cat {
  return "meow" in pet;
}
const pets: (Cat | Dog)[] = [{ meow: () => "meow" }, { bark: () => "woof" }];
for (const p of pets) console.log(isCat(p) ? p.meow() : p.bark());

Output

meow
woof
Filter out nulls with a typed resultTry it yourself
const values = ["a", null, "b", undefined];
const strings = values.filter((v): v is string => typeof v === "string");
console.log(strings.map((s) => s.toUpperCase()));

Output

[ 'A', 'B' ]

Version history

VersionChange
TypeScript 1.6Added

Was this page helpful?