Sub topic 5
Writing User-Defined Type Guards
This chapter assumes that you know basic TypeScript annotations, interfaces, union types, and JavaScript runtime checks such as typeof, instanceof, and in. It also assumes that you can run the TypeScript compiler.
A user-defined type guard is a function that checks a value at runtime and tells TypeScript which type the value has when the check succeeds. Type guards are useful when data enters your program as unknown, such as JSON from an API or a value supplied by a user.
The type predicate
Suppose an application receives user data. The data may have the expected shape, but TypeScript cannot trust it automatically.
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 value: unknown = JSON.parse('{"name":"Ada","age":36}');
if (isUser(value)) {
console.log(value.name.toUpperCase());
console.log(value.age + 1);
}The return type value is User is called a type predicate. It has two parts:
valueis the function parameter being checked.Useris the type TypeScript can use when the function returnstrue.
Inside the if block, TypeScript narrows value from unknown to User. Without the predicate, the compiler would still require checks before reading name or age.
The function must return a real boolean result based on runtime checks. The predicate does not validate data by itself. It describes the result of the validation that your function performs.
Checking object properties safely
A common mistake is to access a property before proving that the value is an object. This is unsafe:
function isUser(value: unknown): value is User {
return typeof value === "object" && typeof value.name === "string";
}The expression value.name is invalid because typeof value === "object" also includes null, arrays, and objects whose properties are unknown. TypeScript correctly rejects this access.
Check the value in stages:
- Confirm that the value is an object.
- Exclude
null. - Confirm that the property exists.
- Check the property's type.
The in operator helps narrow an object before reading a property. TypeScript 4.9 and later support this narrowing pattern.
Guards for unions
Type guards can distinguish members of a union. A discriminated union has a property whose literal value identifies each member.
interface EmailMessage {
kind: "email";
address: string;
}
interface SmsMessage {
kind: "sms";
phone: string;
}
type Message = EmailMessage | SmsMessage;
function isEmailMessage(message: Message): message is EmailMessage {
return message.kind === "email";
}
function destination(message: Message): string {
if (isEmailMessage(message)) {
return message.address;
}
return message.phone;
}The guard makes the relationship between the test and the narrowed type explicit. For a simple discriminant check, an inline condition such as message.kind === "email" would also narrow the value. A named guard is useful when the same check appears in several places or when the logic is more complex.
Common errors
Do not use a type assertion to hide missing validation:
const user = value as User;This tells the compiler to trust you, but it does not inspect the value. Prefer a guard at the boundary where untrusted data enters the program.
Also avoid guards that only check one property when the type requires several properties. A value with a string name but no numeric age is not a valid User.
Exercise
Why does the return type value is User matter in a user-defined type guard?
Show answer
It tells TypeScript to narrow the checked parameter to User in branches where the function returns true. The function's runtime checks must still prove that claim.