Sub topic 10
Writing Your Own Type Guards with Type Predicates
This chapter assumes you know basic TypeScript syntax (functions, interfaces, type aliases), union types such as string | number, and JavaScript control flow (if, switch, the ternary operator). It also assumes you have seen the built-in narrowing checks (typeof, in, instanceof, equality). The examples use TypeScript 4.9 or later.
Why built-in checks are not always enough
Built-in checks work when the compiler can see the check inline. They stop helping when the check is long, is reused in many places, or lives in another function. Suppose you validate an object in a helper and return a plain boolean. The compiler learns nothing from that boolean, so the caller's value keeps its wide type.
A user-defined type guard solves this. It is a function whose return type is a type predicate. The predicate tells the compiler what a true result means about an argument.
The type predicate syntax
A type predicate has the form parameterName is Type and replaces the boolean return type.
type ApiUser = { id: number; name: string };
function isApiUser(value: unknown): value is ApiUser {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
"name" in value &&
typeof value.id === "number" &&
typeof value.name === "string"
);
}
function show(input: unknown): string {
return isApiUser(input) ? input.name : "not a user";
}At runtime, isApiUser returns a boolean. At compile time, the call isApiUser(input) acts as a check the compiler understands. In the true branch, input is ApiUser. In the false branch, the compiler removes ApiUser from the type of input.
The body uses the built-in checks you already know, chained so that each one narrows value a little further. The typeof value === "object" and value !== null checks must come first. Without them, the in operator would be applied to something that might not be an object.
What the compiler does with a predicate
The compiler does not read the guard's body when it checks the caller. It reads only the signature. At each call site it treats the call like a built-in check on the argument.
Two rules follow from this:
- The predicate's type must be assignable to the parameter's type.
value is ApiUseris valid whenvalueisunknown.value is stringis an error whenvalueisnumber, because the two types have nothing in common. - Narrowing in the false branch removes the predicate type from a union. This matters in the next section.
The compiler trusts you
The compiler never checks that a guard's body matches its predicate. If the body is wrong, the compiler still narrows according to the signature. Here is a guard that is subtly wrong:
function isNonEmptyString(value: string | number): value is string {
return typeof value === "string" && value.length > 0;
}
function describe(value: string | number): string {
if (isNonEmptyString(value)) {
return value.toUpperCase();
}
// The compiler believes value is number here.
return value.toFixed(2);
}
console.log(describe(""));This compiles without errors and then throws at runtime. When value is "", the guard returns false. The compiler narrows the false branch to number, but the value is actually a string, so toFixed does not exist on it.
The rule is that a guard must return true exactly when the value is of the predicate type. A guard that returns false for some valid members of the type makes the else branch wrong.
There are two safe ways to fix this. You can make the guard check only the type, as in typeof value === "string", and test the length separately in the caller. Or you can return a plain boolean for checks that are about content rather than type.
Guards for external data
Type guards are most often used at the edge of a program, where data arrives as unknown. A typical case is JSON.parse, which returns any. Assign the result to unknown first, so the compiler forces you to check it.
type ApiUser = { id: number; name: string };
function isApiUser(value: unknown): value is ApiUser {
return (
typeof value === "object" &&
value !== null &&
"id" in value &&
"name" in value &&
typeof value.id === "number" &&
typeof value.name === "string"
);
}
function parseUser(json: string): ApiUser {
const data: unknown = JSON.parse(json);
if (!isApiUser(data)) {
throw new Error("Invalid user payload");
}
return data;
}
console.log(parseUser('{"id": 1, "name": "Ada"}').name);The guard checks every property that ApiUser declares. If you add a field to ApiUser and forget to update the guard, the compiler will not warn you. Keep the type and the guard next to each other, and add a test that fails when they drift apart.
For larger payloads, a schema validation library gives you the same result with less hand-written code. The idea is the same: a runtime check whose result carries a static type.
Composing and reusing guards
Guards are ordinary functions, so you can build small ones and combine them. A generic guard works for any type:
function isDefined<T>(value: T | null | undefined): value is T {
return value != null;
}
const ids: (number | null)[] = [1, null, 3];
const present: number[] = ids.filter(isDefined);
console.log(present);The type parameter T is inferred from the argument. For (number | null)[], the compiler infers T as number. Passing a guard to filter is how you get number[] instead of (number | null)[]. A plain callback such as v => v !== null does not do this in older compilers.
A guard can also take another guard as an argument. This checks that an unknown value is an array whose items all pass a given check:
function isString(value: unknown): value is string {
return typeof value === "string";
}
function isArrayOf<T>(
value: unknown,
guard: (item: unknown) => item is T
): value is T[] {
return Array.isArray(value) && value.every(guard);
}
const raw: unknown = JSON.parse('["a", "b"]');
if (isArrayOf(raw, isString)) {
console.log(raw.join(", "));
}Here the predicate refers to value, the first parameter, while the second parameter is the callback. A predicate always names one parameter.
Guards on methods and inferred predicates
A method can narrow this with a this is predicate. This is useful for classes whose state decides which members are safe to use.
class FileHandle {
constructor(public path: string | null) {}
isOpen(): this is { path: string } {
return this.path !== null;
}
}
const handle = new FileHandle("notes.txt");
if (handle.isOpen()) {
console.log(handle.path.toUpperCase());
}TypeScript 5.5 and later can infer a type predicate for a simple function that returns a check on its parameter. For example, (v: string | null) => v !== null is inferred as v is string. Inference only applies when the function returns true exactly when the narrowed type holds, which avoids the bug in isNonEmptyString. Write the predicate explicitly when the guard is exported, when it is complex, or when you must support older compilers.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Guard returns `false` for some valid members of the predicate type | The else branch is narrowed wrongly and can crash at runtime | Check only the type in the guard, and test content separately |
| Guard checks fewer properties than the type declares | Callers read properties that may be missing | Check every required property, and test the guard |
| Predicate names the wrong parameter | The wrong variable is narrowed | Check that the name before `is` matches the argument you mean |
| Guard returns a truthy value instead of a boolean | Compile error, because predicates must return `boolean` | Return a comparison or wrap the result in `Boolean(...)` |
| Using `as ApiUser` instead of a guard | The compiler stops checking, and bad data passes through silently | Use a guard, or throw when validation fails |
Exercise
A teammate writes function isPositive(n: number | string): n is number { return typeof n === "number" && n > 0; }. Describe a call where the compiler and the runtime disagree, and say how to fix the guard.
Show answer
Calling it with -5 or 0 returns false, so the else branch narrows n to string, but the value is a number. Code in the else branch that calls a string method, such as n.toUpperCase(), compiles and then throws. The fix is to make the guard check only the type, typeof n === "number", and test the sign in the caller. Another option is to return a plain boolean, because "positive" is a property of the value and not of its type.
Exercise
Write the signature of a generic guard isOneOf that takes a value of type unknown and a readonly array of strings, and narrows the value to the union of the array's members. Then say why the array parameter must be typed with a type parameter.
Show answer
One signature is function isOneOf<T extends string>(value: unknown, options: readonly T[]): value is T. The body can be return typeof value === "string" && (options as readonly string[]).includes(value);. The type parameter T lets the compiler read the literal members from the array argument, for example "red" | "green" for ["red", "green"] as const. If options were typed string[], the predicate could only narrow to string, which is no better than a typeof check.