Sub topic 6
Type Predicates and Assertion Functions for Brands
Prerequisites
This chapter assumes you know TypeScript type aliases, intersection types, functions, and generics. It also assumes you have seen branded types such as Email = string & { ... }. A brand is checked only by TypeScript, so you still need runtime validation before creating one.
A type predicate is a function return type that tells TypeScript when a condition is true. Its form is value is SomeType.
Type predicates narrow values
Start with a reusable brand:
declare const brand: unique symbol;
type Brand<T, B extends string> = T & {
readonly [brand]: B;
};
type Email = Brand<string, "Email">;
function isEmail(value: string): value is Email {
return /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value);
}
function sendReceipt(to: Email): void {
console.log(`Sending receipt to ${to}`);
}
function handleInput(raw: string): void {
if (isEmail(raw)) {
sendReceipt(raw); // raw is Email inside this block
} else {
console.log("The address is invalid");
}
}
handleInput("[email protected]");The expression isEmail(raw) returns a normal Boolean at runtime. The value is Email part adds information for the compiler. In the true branch, TypeScript narrows raw from string to Email.
A predicate does not create a brand by itself. The function's implementation must be trustworthy. If the check is too weak, invalid data can receive a valid-looking type.
For data from files, HTTP requests, or users, accept unknown rather than string. This forces the guard to check the input's type before using string operations.
function isEmailValue(value: unknown): value is Email {
return (
typeof value === "string" &&
/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value)
);
}
function parseEmail(value: unknown): Email {
if (!isEmailValue(value)) {
throw new Error("Expected a valid email address");
}
return value;
}
const email = parseEmail("[email protected]");
sendReceipt(email);Assertion functions
An assertion function throws when a condition is false. Its return type uses asserts:
type PositiveInt = Brand<number, "PositiveInt">;
function assertPositiveInt(
value: number
): asserts value is PositiveInt {
if (!Number.isInteger(value) || value <= 0) {
throw new RangeError(`Expected a positive integer, got ${value}`);
}
}
function repeat(text: string, count: PositiveInt): string {
return text.repeat(count);
}
function makeMessage(count: number): string {
assertPositiveInt(count);
return repeat("ab", count); // count is PositiveInt here
}
console.log(makeMessage(3));The function returns void when validation succeeds. If it returns at all, TypeScript narrows value to PositiveInt. If validation fails, the function must throw or otherwise never return. A faulty assertion can make the program unsafe while still compiling.
Choosing the form
Use a type predicate when invalid input is an expected possibility and the caller can choose what to do. Use an assertion function when invalid input should stop the current operation.
Keep validation at the boundary where untrusted data enters the program. Internal functions can then require the brand and avoid repeating the same checks.
Exercise
What is the difference between value is Email and asserts value is Email?
Show answer
A type predicate returns a Boolean and narrows the value in a true branch. An assertion function throws on failure and narrows the value after the call returns.