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
Syntax
function f(x: unknown): x is T
Examples
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
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
| Version | Change |
|---|---|
| TypeScript 1.6 | Added |
Related
unknown· The type-safe 'anything': a value of type unknown must be narrowed (checked) before you can use it, unlike any.assertion functions (asserts x is T)· A function declared 'asserts value is Type' throws if the check fails, and narrows the type after the call.- TypeScript keyof, typeof and Indexed Access · tutorial