Sub topic 10
Writing Your Own Type Guards with Type Predicates
Assume you know TypeScript union types, functions, object types, and basic control flow. You also need to understand that TypeScript types disappear when JavaScript runs. A type guard is runtime code that checks a value and gives TypeScript information about the result.
Built-in checks such as typeof and in handle many cases. For application data, you often need a reusable check for a larger structure. A user-defined type guard is a function whose return type uses the form value is SomeType.
The type predicate contract
Consider data received from an API:
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 showUser(input: unknown): string {
if (isApiUser(input)) {
return `${input.id}: ${input.name}`;
}
return "Not a valid user";
}
console.log(showUser({ id: 7, name: "Mina" }));
console.log(showUser({ id: "7", name: "Mina" }));The expression value is ApiUser is a type predicate. When the function returns true, TypeScript treats the checked value as an ApiUser in that branch.
The parameter in the predicate must be a parameter of the function. The function should return true only when every property required by the target type has been checked.
Check unknown values safely
unknown is safer than any for external data. You cannot read properties or call methods on an unknown value until a check narrows it.
The order of checks matters. First confirm that the value is an object and is not null. Then check that the properties exist. Finally check each property’s type.
A guard can describe a union as well as an object type:
type Success = { status: "success"; data: string };
type Failure = { status: "failure"; message: string };
type Result = Success | Failure;
function isSuccess(result: Result): result is Success {
return result.status === "success";
}
function describe(result: Result): string {
if (isSuccess(result)) {
return `Received: ${result.data}`;
}
return `Failed: ${result.message}`;
}
console.log(describe({ status: "success", data: "ready" }));Here, the guard does not inspect unknown input. It gives a name to a useful check that already narrows a union.
Guards with array methods
A type predicate is especially useful with filter. Without a predicate, TypeScript may keep the original union in the resulting array.
const values: (string | null)[] = ["a", null, "b"];
const strings: string[] = values.filter(
(value): value is string => value !== null
);
console.log(strings.map((value) => value.toUpperCase()));The callback says that a true result means the value is a string, so strings becomes string[].
Keep guards honest
A type guard is an executable claim about data. Keep it near the type it validates, test both accepted and rejected inputs, and update it when the type changes. Do not use a type assertion such as input as ApiUser merely to silence the compiler. An assertion skips validation; a guard performs it.
Exercise
What does value is ApiUser tell TypeScript, and what must the function do at runtime?
Show answer
It tells TypeScript that a true result narrows value to ApiUser. The function must actually verify every property and type required by ApiUser.