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(", "));- Expected result: The program prints ADA, GRACE; names is inferred as string[].
- The guard excludes numbers and null at runtime.
- 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