Sub topic 13
Custom type guards
This chapter assumes you know how to define a discriminated union and narrow it with switch and if. It also assumes strict: true in your tsconfig. Built-in narrowing works when the compiler already knows the value is a Shape. A custom type guard covers the case where it doesn't, such as parsed JSON, a function parameter typed unknown, or a helper you want to reuse.
What a type guard is
A type guard is an expression that narrows a type inside a conditional. You have already used several:
typeof value === "string"value instanceof Date"radius" in shapeshape.kind === "circle"
The compiler understands each of these because they are built into the language. A custom type guard is a function you write whose return type tells the compiler what a true result means.
Type predicates
A type predicate is a return type of the form parameter is Type. At runtime the function returns an ordinary boolean. At compile time, a call in a condition narrows the argument.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number };
function area(shape: Shape): number {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.size ** 2;
case "rectangle":
return shape.width * shape.height;
}
}
function isShape(value: unknown): value is Shape {
if (typeof value !== "object" || value === null) return false;
const v = value as Record<string, unknown>;
switch (v.kind) {
case "circle":
return typeof v.radius === "number";
case "square":
return typeof v.size === "number";
case "rectangle":
return typeof v.width === "number" && typeof v.height === "number";
default:
return false;
}
}
const parsed: unknown = JSON.parse('{"kind":"square","size":3}');
if (isShape(parsed)) {
console.log(area(parsed)); // 9
}Inside the if, parsed has type Shape. Outside it, parsed is still unknown.
The guard has three steps:
- It rules out non-objects and
null.typeof nullis"object", so thenullcheck is required. - It uses
as Record<string, unknown>to read properties safely. This cast is acceptable because the guard is the one place that checks the data. Nothing is claimed beyondunknownvalues. - It switches on the discriminant and checks the fields that belong to that variant.
Guards for a single variant
Predicates are useful when you want to pick out one member. Combined with Extract, the guard stays in sync with the union:
type Circle = Extract<Shape, { kind: "circle" }>;
function isCircle(shape: Shape): shape is Circle {
return shape.kind === "circle";
}
const shapes: Shape[] = [
{ kind: "circle", radius: 1 },
{ kind: "square", size: 2 },
{ kind: "circle", radius: 3 },
];
const circles = shapes.filter(isCircle); // Circle[]
const radii = circles.map((c) => c.radius);
console.log(radii); // [1, 3]Without the predicate, shapes.filter((s) => s.kind === "circle") returns Shape[] in older compilers, and c.radius would not compile. TypeScript 5.5 and later infer a predicate for simple arrow functions like that one. An explicit named guard works in every version, can be reused, and gives the intent a name.
When the parameter's declared type is a union, a predicate also narrows the false branch. After if (isCircle(shape)) { ... } else { ... }, shape in the else block is the union without Circle. When the parameter is unknown, the false branch stays unknown, because the compiler can't subtract a type from unknown.
Assertion functions
A type guard returns a boolean and you branch on it. Sometimes you would rather throw and continue with a narrowed value. An assertion function has the return type asserts value is T:
function assertShape(value: unknown): asserts value is Shape {
if (!isShape(value)) {
throw new TypeError(`Not a valid Shape: ${JSON.stringify(value)}`);
}
}
function loadArea(json: string): number {
const data: unknown = JSON.parse(json);
assertShape(data);
return area(data); // data is Shape from here on
}
console.log(loadArea('{"kind":"rectangle","width":2,"height":5}')); // 10Choose a boolean guard when invalid input is a normal outcome you handle in place. Choose an assertion when invalid input is a bug or should abort the operation. Assertion functions have a call-site restriction: they must be called through an identifier with an explicit type annotation, such as a function declaration, which is why assertShape is declared with function.
Returning a Result instead
A guard answers yes or no and discards the reason. For input validation you often want a message. You can combine the guard with the Result type from earlier in this tutorial:
type Result<T, E> =
| { ok: true; value: T }
| { ok: false; error: E };
function parseShape(json: string): Result<Shape, string> {
let data: unknown;
try {
data = JSON.parse(json);
} catch {
return { ok: false, error: "Invalid JSON" };
}
if (!isShape(data)) {
return { ok: false, error: "JSON does not describe a Shape" };
}
return { ok: true, value: data };
}
const outcome = parseShape('{"kind":"circle","radius":"big"}');
console.log(outcome.ok ? area(outcome.value) : outcome.error);
// JSON does not describe a ShapeThe guard stays small and testable, and the Result wrapper decides how failures are reported.
Choosing a narrowing tool
| Situation | Tool |
|---|---|
| Value is already a union and you want one member | `switch` or `===` on the discriminant |
| Primitive or class check | `typeof`, `instanceof` |
| Value is `unknown` or `any` | Custom type guard |
| Same check used in several places | Custom type guard |
| Invalid input should stop execution | Assertion function |
| Input may fail and the caller needs a reason | Guard inside a function returning `Result` |
Gotchas
The compiler trusts your predicate
TypeScript does not check that the body of a guard matches its predicate. This compiles without error:
function isCircleWrong(shape: Shape): shape is Circle {
return true;
}After this call, every Shape is treated as a circle, and shape.radius is undefined for squares. The type system is only as accurate as the guard. A predicate is a claim the compiler accepts without checking.
Two habits help. Write guards so each true return is backed by explicit checks, and unit test them with valid and invalid samples for every variant.
Guards can be incomplete
isShape accepts { "kind": "circle", "radius": -5 }, { "kind": "square", "size": NaN }, and objects with extra properties. Each typeof check passes for those values. If your domain forbids them, the guard must check them too:
function isPositive(n: unknown): n is number {
return typeof n === "number" && Number.isFinite(n) && n > 0;
}Decide how strict each guard should be. The type number cannot express "positive", so anything stricter than the type is a runtime rule that no compiler checks.
Keep guards in step with the union
Adding a variant to Shape does not make isShape fail to compile. The default: return false branch silently rejects the new variant. Two fixes work:
- Use an exhaustive object keyed by
Shape["kind"], so a missing key is a compile error:
type ShapeKind = Shape["kind"];
const validators: Record<ShapeKind, (v: Record<string, unknown>) => boolean> = {
circle: (v) => typeof v.radius === "number",
square: (v) => typeof v.size === "number",
rectangle: (v) =>
typeof v.width === "number" && typeof v.height === "number",
};
function isShapeKind(kind: unknown): kind is ShapeKind {
return typeof kind === "string" && Object.hasOwn(validators, kind);
}
function isShapeChecked(value: unknown): value is Shape {
if (typeof value !== "object" || value === null) return false;
const v = value as Record<string, unknown>;
return isShapeKind(v.kind) && validators[v.kind](v);
}Adding triangle to Shape now fails at validators until you supply a check. Object.hasOwn needs a target of ES2022 or later. On older targets, use Object.prototype.hasOwnProperty.call(validators, kind).
- Use a schema library that derives both the type and the validator from one definition. This removes the duplication, at the cost of a dependency.
Do not use a guard where narrowing already works
If shape is typed Shape, switch (shape.kind) already narrows it and gives you exhaustiveness checking. A custom guard adds nothing there and can hide mistakes. Reserve guards for values whose type the compiler cannot establish.
Exercise
A teammate writes function isSquare(s: Shape): s is Extract<Shape, { kind: "square" }> { return s.kind !== "circle"; }. It compiles. What is wrong, and what does the compiler do about it?
Show answer
The body returns true for rectangles as well as squares, so the predicate claims more than the code checks. The compiler does not verify predicate bodies, so it accepts the function and treats rectangles as squares after a true result. Reading s.size on a rectangle then gives undefined at runtime. The fix is return s.kind === "square";.
Exercise
You have const data: unknown = JSON.parse(text) and you call isShape(data) in an if with an else branch. What is the type of data in each branch?
Show answer
In the if branch, data is Shape. In the else branch, data is still unknown, because TypeScript cannot remove a type from unknown.
Exercise
Write a guard isCircleList(values: unknown[]): values is Circle[] that checks every element. Why is checking only the first element a mistake?
Show answer
One correct implementation is return values.every((v) => isShape(v) && v.kind === "circle");. Checking only the first element lets later elements of another variant through, and the predicate would then claim the whole array is Circle[]. The compiler would trust that claim.