TypeScript type guards
- Version
- es2025
- Review
- Draft
Summary#
A type guard lets TypeScript narrow a value on a code path. A user-defined predicate describes the type that holds when its runtime check returns true.
Syntax#
function isString(value: unknown): value is string {
return typeof value === "string";
}
Example#
function isString(value: unknown): value is string {
return typeof value === "string";
}
const values: unknown[] = [3, "paper", undefined, "pen"];
const names = values.filter(isString);
console.log(names.map((name) => name.toUpperCase()).join(", "));
Expected output#
PAPER, PEN. The predicate narrows the filtered array to string[].
Common mistakes#
Write a runtime check that supports the promised type in both branches. A test for short strings alone cannot promise value is string, since a long string would reach the false branch. When guarding an object, check null separately because typeof null is "object".
Version applicability#
TypeScript 1.6 added user-defined type predicates. The syntax and example need TypeScript 3.0 for unknown. The emitted JavaScript uses standard runtime checks.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0