Sub topic 5
Writing user-defined type guards
This chapter assumes you know basic TypeScript syntax (interfaces, unions, type annotations) and the JavaScript operators typeof, instanceof, and in. It covers how to write your own functions that tell the compiler what type a value has after a runtime check.
Why built-in narrowing is not enough
The previous chapter showed how typeof, instanceof, and in narrow an unknown value. Those checks work well for primitives and class instances. They stop being enough when you need to confirm the shape of an object, for example one parsed from JSON.
You could write the full check inline every time you receive such an object. That repeats code, and each copy can drift from the others. A user-defined type guard wraps the check in one function and tells the compiler what a true result means.
The type predicate
A type guard is a function whose return type is a type predicate. The predicate has the form parameterName is Type.
function isString(value: unknown): value is string {
return typeof value === "string";
}
const input: unknown = "hello";
if (isString(input)) {
console.log(input.toUpperCase()); // input is string here
}At runtime the function returns an ordinary boolean. At compile time the predicate adds one rule: when the call returns true, the argument has type string in that branch. When it returns false, the compiler removes string from the argument's type in the else branch.
The compiler does not verify that your function body matches the predicate. It trusts what you wrote. This is the central risk of type guards, and a later section returns to it.
A guard for an object shape
The most common use is validating data whose shape you do not control. This guard checks that an unknown value is a User.
interface User {
name: string;
age: number;
}
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
"name" in value &&
typeof value.name === "string" &&
"age" in value &&
typeof value.age === "number"
);
}
const parsed: unknown = JSON.parse('{"name":"Ada","age":36}');
if (isUser(parsed)) {
console.log(parsed.name.toUpperCase());
}Each line of the check does a specific job:
typeof value === "object"narrowsunknowntoobject | null.value !== nullremovesnull. This step is needed becausetypeof nullis also"object"."name" in valuenarrowsvalueto an object that has anameproperty. Before TypeScript 4.9,indid not narrowobjectthis way, so the next line would fail to compile.typeof value.name === "string"checks the property's type. Without this,value.namewould beunknown.
The same sequence repeats for age. The && chain stops at the first failure, so a later check never runs on a value that failed an earlier one.
Why the order matters
If you swap the first two conditions, value !== null runs on an unknown value. That is allowed, but the in operator on a possible null throws a TypeError at runtime. Always rule out null before using in.
What a guard must check
A guard is only as safe as its body. Consider these two guards for the same type:
interface User {
name: string;
age: number;
}
// Weak: checks only that the value is a non-null object.
function isUserWeak(value: unknown): value is User {
return typeof value === "object" && value !== null;
}
// Strong: checks each property.
function isUserStrong(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
"name" in value &&
typeof value.name === "string" &&
"age" in value &&
typeof value.age === "number"
);
}
const bad: unknown = { name: 42 };
console.log(isUserWeak(bad)); // true, but bad is not a User
console.log(isUserStrong(bad)); // falseisUserWeak compiles without complaint. After it returns true, the compiler treats the value as a User, and user.name.toUpperCase() throws at runtime. This is the same kind of failure that any allows, and it is hidden behind a function that looks like validation.
Guards for unions and arrays
Guards compose. You can build a guard for an array by checking Array.isArray and then applying an element guard.
interface User {
name: string;
age: number;
}
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
"name" in value &&
typeof value.name === "string" &&
"age" in value &&
typeof value.age === "number"
);
}
function isArrayOf<T>(
value: unknown,
guard: (item: unknown) => item is T
): value is T[] {
return Array.isArray(value) && value.every(guard);
}
const data: unknown = JSON.parse('[{"name":"Ada","age":36},{"name":"Alan","age":41}]');
if (isArrayOf(data, isUser)) {
for (const user of data) {
console.log(`${user.name} is ${user.age}`);
}
}isArrayOf takes the element guard as an argument. The generic parameter T is inferred from the guard's predicate, so data becomes User[] inside the if.
A guard also narrows a union to one member. Given string | number, an isString guard leaves number in the else branch.
function isString(value: unknown): value is string {
return typeof value === "string";
}
function describe(value: string | number): string {
if (isString(value)) {
return `string of length ${value.length}`;
}
return `number ${value.toFixed(2)}`; // value is number here
}
console.log(describe("abc"));
console.log(describe(3.14159));The false branch and "if and only if"
When a guard returns false, the compiler narrows the argument by excluding the predicate type. That is only correct if the guard returns true for every value of that type. Consider a guard that is too strict:
function isPositive(value: number): value is number {
return value > 0;
}
function check(n: number): void {
if (isPositive(n)) {
console.log("positive");
} else {
// The compiler narrows n to never here, because it believes
// every number makes isPositive return true.
console.log("not positive");
}
}
check(-1);The predicate claims every number passes, so the else branch sees n as never. The code still runs, but any use of n there would be an error, and the type is wrong. The lesson is that a predicate means "true if and only if". If your function can return false for a value that really has the predicate type, narrowing in the else branch is incorrect. Use a plain boolean return type for checks like this one.
Type guards on methods and `this`
A method can narrow this with a this is Type predicate. This is less common, but it appears in class hierarchies.
class FileEntry {
constructor(public path: string) {}
isDirectory(): this is DirectoryEntry {
return this instanceof DirectoryEntry;
}
}
class DirectoryEntry extends FileEntry {
children: FileEntry[] = [];
}
const entry: FileEntry = new DirectoryEntry("/tmp");
if (entry.isDirectory()) {
console.log(entry.children.length);
}Assertion functions
A related form uses asserts instead of a boolean result. The function throws if the check fails, and the compiler narrows the value for all code after the call.
function assertIsString(value: unknown): asserts value is string {
if (typeof value !== "string") {
throw new TypeError(`Expected string, got ${typeof value}`);
}
}
function shout(input: unknown): string {
assertIsString(input);
return input.toUpperCase(); // input is string from here on
}
console.log(shout("hi"));Use a predicate guard when both outcomes are valid paths. Use an assertion function when a failed check should stop the program flow. Assertion functions must be called through an explicitly typed reference, such as a declared function, for the narrowing to apply.
Choosing between guards, assertions, and `as`
| Tool | Runtime check | Compiler narrowing | Use when |
|---|---|---|---|
| Type predicate (`x is T`) | Yes, you write it | In the `true` branch, and the opposite in `false` | Both outcomes are handled |
| Assertion function (`asserts x is T`) | Yes, throws on failure | For all code after the call | Failure should abort |
| Type assertion (`x as T`) | None | Forced by you | You know something the compiler cannot verify |
A type assertion produces no runtime code. It tells the compiler to believe you. A guard performs a real check, so prefer it for data from outside your program.
Common mistakes
- Returning
trueafter a shallow check. Checking onlytypeof value === "object"accepts arrays,null(unless excluded), and objects of any shape. - Forgetting
null.typeof null === "object", so every object guard needs an explicitvalue !== null. - Ignoring optional and nested properties. If
Userhas an optional field, the guard must accept both its absence and a value of the right type. Nested objects need their own checks, usually a second guard. - Using a wide guard for a narrow type. A guard for
"a" | "b"must compare against both literals, not justtypeof value === "string". - Checking array contents by sampling. Testing only
value[0]lets bad elements through. Useevery. - Writing a guard where a schema library fits better. Large or deeply nested shapes make hand-written guards long and easy to get wrong. A runtime validation library generates the check from a single definition. For small shapes, a guard has no dependencies and is easy to read.
Putting it together
The diagram shows how a guard sits between untrusted input and typed code.
The branch on isUser is the only place where the type changes. Every other step relies on the guard being correct, which is why the guard deserves tests.
Testing a guard
A guard is small enough to test with a handful of cases. Include the values most likely to slip through.
interface User {
name: string;
age: number;
}
function isUser(value: unknown): value is User {
return (
typeof value === "object" &&
value !== null &&
"name" in value &&
typeof value.name === "string" &&
"age" in value &&
typeof value.age === "number"
);
}
const cases: Array<[unknown, boolean]> = [
[{ name: "Ada", age: 36 }, true],
[{ name: "Ada" }, false],
[{ name: "Ada", age: "36" }, false],
[null, false],
[[], false],
["Ada", false],
];
for (const [input, expected] of cases) {
const actual = isUser(input);
console.log(actual === expected ? "ok" : "FAIL", JSON.stringify(input));
}Running this prints ok for every case. If you replace isUser with isUserWeak from earlier, the cases for a missing age, a string age, and an array all print FAIL.
Summary of rules
- A predicate
x is Tmakes the compiler trust thattruemeansxhas typeT. - The function body is your responsibility. The compiler does not verify it.
- Rule out
nullbefore usinginor property access on anunknownobject. - A predicate should be true if and only if the value has the type, so that the
elsebranch narrows correctly. - Use
asserts x is Twhen a failed check should throw. - Use a guard rather than
asfor data that comes from outside your program.
Exercise
Write a type guard isPoint(value: unknown): value is { x: number; y: number }. Then say what goes wrong if the guard body is just return typeof value === "object" && value !== null; and the code later reads value.x.toFixed(1) after the guard returns true.
Show answer
Guard:
function isPoint(value: unknown): value is { x: number; y: number } {
return (
typeof value === "object" &&
value !== null &&
"x" in value &&
typeof value.x === "number" &&
"y" in value &&
typeof value.y === "number"
);
}
With the shallow body, the compiler still treats any non-null object as a point, because it trusts the predicate. A value such as {} or { x: "1" } passes, so value.x is undefined or a string and value.x.toFixed(1) throws a TypeError at runtime, with no compile-time warning.
Exercise
A guard isEven(n: number): n is number returns n % 2 === 0. What type does the compiler give n in the else branch, and why is that a problem?
Show answer
It gives n the type never, because the predicate claims every number is a match, so excluding number leaves nothing. Odd numbers do reach the else branch at runtime, so the type is wrong and any use of n there would be rejected or misleading. The function should return plain boolean, since "even" is not a type that TypeScript can express.