Sub topic 13
Custom Type Guards for Discriminated Unions
Assume you know basic TypeScript types, functions, if statements, and discriminated unions. This chapter focuses on a boundary that the compiler cannot check: data received from JSON, a network request, or another JavaScript module.
Why a custom type guard is needed
TypeScript checks values while it compiles your code. It does not check the contents of a JSON response at runtime. JSON.parse returns a value that may have any shape.
A custom type guard is a function that checks a value and tells TypeScript which type it has when the function returns true. Its return type uses the form value is SomeType.
The predicate is a promise. TypeScript trusts it. The function must therefore perform every runtime check needed to support that promise.
Build a guard for a union
This example accepts an unknown value. The unknown type means that code must check the value before using it.
type Shape =
| { kind: "circle"; radius: number }
| { kind: "square"; size: number }
| { kind: "rectangle"; width: number; height: number };
function isShape(value: unknown): value is Shape {
if (
typeof value !== "object" ||
value === null ||
Array.isArray(value)
) {
return false;
}
const record = value as Record<string, unknown>;
switch (record.kind) {
case "circle":
return typeof record.radius === "number" &&
Number.isFinite(record.radius);
case "square":
return typeof record.size === "number" &&
Number.isFinite(record.size);
case "rectangle":
return typeof record.width === "number" &&
Number.isFinite(record.width) &&
typeof record.height === "number" &&
Number.isFinite(record.height);
default:
return false;
}
}
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;
}
}
const input: unknown =
JSON.parse('{"kind":"rectangle","width":4,"height":3}');
if (isShape(input)) {
console.log(area(input));
} else {
console.error("The input is not a valid shape");
}Before the if, input is unknown, so area(input) would be an error. Inside the true branch, the predicate narrows input to Shape. The discriminant, kind, then narrows it again to the matching member when area uses its switch.
The guard checks the following:
- The value is an object and is not
null. - The value is not an array.
kindis one of the expected literal values.- Each member has the required numeric properties.
Keep the guard honest
A type guard that checks only typeof value === "object" is unsafe. It could accept {} and still claim that the value is a Shape. Later code might read a missing radius or width.
The compiler does not compare the function body with the predicate. If you write this, TypeScript accepts the claim:
function isShape(value: unknown): value is Shape {
return true;
}The function is compile-time valid but runtime-unsafe. Treat type guards as validation code, and test them with valid and invalid examples.
> warning > A type annotation does not validate external data. Validate first, then narrow the value with a trustworthy guard.
When to use one
Use a custom guard when untrusted data enters your program and you need the same check in several places. For a single small check, a local validation function may be clearer. For larger schemas, a validation library can reduce repeated checks, but the same rule applies: successful validation must justify the type you use afterward.
Exercise
Why does isShape(input) allow input to be passed to area inside the if branch?
Show answer
Its return type is input is Shape, so TypeScript narrows the unknown value to Shape when the function returns true.