Codectionary / Developer documentation / TypeScript

Reusable Type Guards with Type Predicates

A predicate return type such as value is string tells TypeScript how a boolean result narrows a value. This is useful for validation helpers and filtering. The compiler trusts the declared predicate, so its implementation must check the claimed condition accurately.

Syntax

function isText(value: unknown): value is string { return typeof value === "string"; }

Examples

Reusable Type Guards with Type Predicates: working example

Run this standalone example after compiling with TypeScript 5.4+ in strict mode, targeting ES2022. Expected result: The program prints ADA, GRACE; names is inferred as string[].

function isText(value: unknown): value is string {
  return typeof value === "string";
}
const mixed: unknown[] = ["Ada", 3, null, "Grace"];
const names = mixed.filter(isText);
console.log(names.map(name => name.toUpperCase()).join(", "));
  1. Expected result: The program prints ADA, GRACE; names is inferred as string[].
  2. The guard excludes numbers and null at runtime.
  3. The predicate signature lets filter preserve the narrowed element type.

Best practices

  • Keep guards aligned with the full shape they claim to validate.
  • Do not use an assertion inside a guard as a substitute for checking input.

Runtime & versions

Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

TypeScript Handbook

Specifications & further reading