Sub topic 6
Type predicates and assertion functions for brands
This chapter assumes you know how to define a branded type with Brand<T, B>. It also assumes you can read generic functions and union narrowing, and that you know types are erased at runtime. Here you learn the two TypeScript features that let a runtime check produce a branded type without a cast at each call site: type predicates and assertion functions.
The problem a check has to solve
A brand is a compile-time claim: "this string is a valid email." Nothing at runtime enforces that claim. The only way to create a branded value is to tell the compiler it is one, and a cast does that without looking at the value.
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type Email = Brand<string, "Email">;
const looksFine = "not-an-email" as Email; // compiles, but the claim is falseType predicates and assertion functions tie the claim to a real check. The check runs, and only if it passes does the compiler treat the value as branded. The cast then lives in one place, or disappears entirely.
Type predicates: `value is Email`
A type predicate is a return type of the form parameter is Type. At runtime the function returns a boolean. At compile time, a true result narrows the argument to Type in the code that depends on that result.
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 sendWelcome(to: Email): string {
return `Welcome mail queued for ${to}`;
}
function handleSignup(input: string): string {
if (isEmail(input)) {
return sendWelcome(input); // input is Email here
}
return "Please enter a valid email address";
}
console.log(handleSignup("[email protected]"));
console.log(handleSignup("ada"));Calling sendWelcome(input) outside the if block is a compile error, because input is still a plain string there. The compiler forces the check to happen first.
Narrowing follows normal control flow, so these forms work too:
- Early return:
if (!isEmail(input)) return;narrows everything after it. - Logical operators:
isEmail(input) && sendWelcome(input). - Array filtering:
values.filter(isEmail)returnsEmail[], becausefilterhas an overload that accepts a predicate.
Predicates accept `unknown`
The parameter of a predicate does not have to be string. Accepting unknown lets one function check data of any origin.
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type PositiveInt = Brand<number, "PositiveInt">;
function isPositiveInt(value: unknown): value is PositiveInt {
return typeof value === "number" && Number.isInteger(value) && value > 0;
}
const raw: unknown = 42;
if (isPositiveInt(raw)) {
const n: PositiveInt = raw; // narrowed from unknown to PositiveInt
console.log("ok", n);
}This form is the one to use when the value comes from JSON, a form field, or another source you cannot trust.
A predicate is a promise the compiler does not verify
The compiler checks that the body returns a boolean. It does not check that the body matches the type in the predicate. This predicate compiles and is wrong:
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type PositiveInt = Brand<number, "PositiveInt">;
function isPositiveIntWrong(n: number): n is PositiveInt {
return n > 0; // accepts 1.5, which is not an integer
}Every branded value rests on the quality of the function that produced it, so keep these functions small and test them. Predicates also make a claim in the other direction. When a predicate returns false, the compiler narrows the false branch to "not this type." If you accept a union such as Email | PhoneNumber and a real email fails your check, the else branch will wrongly treat it as a phone number.
Assertion functions: `asserts value is Email`
A predicate returns a boolean, and the caller decides what to do on failure. An assertion function takes the other approach. It throws when the check fails, and when it returns normally the argument is narrowed for the rest of the scope.
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type PositiveInt = Brand<number, "PositiveInt">;
function assertPositiveInt(n: number): asserts n is PositiveInt {
if (!Number.isInteger(n) || n <= 0) {
throw new RangeError(`Expected a positive integer, got ${n}`);
}
}
function repeat(times: PositiveInt, text: string): string {
return text.repeat(times);
}
function run(n: number): string {
assertPositiveInt(n);
return repeat(n, "ab"); // n is PositiveInt from here on
}
console.log(run(3)); // abababThe caller needs no if and no else. The invalid case is handled by the exception, so the code after the call is the valid path. This style suits internal code where an invalid value is a bug, and request handlers that already translate exceptions into error responses.
The explicit annotation rule
An assertion function must be called through a name whose type is written out. A function declaration satisfies this. A const holding an arrow function does not, because its type is inferred.
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type Email = Brand<string, "Email">;
const assertEmail: (value: string) => asserts value is Email = (value) => {
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value)) {
throw new Error(`Invalid email: ${value}`);
}
};
function demo(input: string): void {
assertEmail(input);
const email: Email = input;
console.log(email);
}Without the annotation on assertEmail, the call fails with error 2775: "Assertions require every name in the call target to be declared with an explicit type annotation." The same rule applies to methods reached through a variable, such as validators.assertEmail(x), when validators has no declared type.
Narrowing does not always last
Narrowing from either feature is dropped when TypeScript can no longer be sure the variable holds the checked value:
- Reassigning the variable (
input = other) discards the narrowing. - A
letvariable captured by a callback or closure is not narrowed inside that function, because it could change before the callback runs. - Narrowing applies to the checked reference. If you check
user.email, the narrowing is lost whenuseris reassigned or when a function call could have changed the property.
Prefer const bindings, or capture the narrowed value in a new const before using it in a callback.
Returning the value: parse functions
The spine's parseEmail combines a predicate with a throw. Instead of narrowing the caller's variable, it returns a branded value.
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 parseEmail(value: string): Email {
if (!isEmail(value)) {
throw new Error(`Invalid email: ${value}`);
}
return value; // narrowed to Email, so no cast is needed
}Here the predicate does the work and return value needs no as. The only place a cast could appear is inside isEmail's own implementation, and there it is not needed either, because the predicate's return type carries the claim.
Choosing between the forms
| Form | Signature | On invalid input | Best for |
|---|---|---|---|
| Type predicate | `(v: string) => v is Email` | Returns `false` | Branching, filtering arrays, optional handling |
| Assertion function | `(v: string) => asserts v is Email` | Throws | Internal invariants, code where failure is exceptional |
| Parse function | `(v: string) => Email` | Throws (or returns a result type) | Producing a new branded value to store or pass on |
A common layout is one predicate per brand, with the assertion and parse functions built on top of it. The validation rule then exists in a single place.
Common mistakes
- Putting the validation in one place and the cast in another, so the two drift apart. Keep the check and the brand claim in the same function.
- Writing
const assertX = (...) : asserts ...with no annotation on the variable, then calling it and seeing error 2775. - Writing a predicate that returns
truefor values the brand's name forbids, such asNaNpassing a number check because onlytypeofwas tested. - Assuming narrowing persists inside callbacks on
letvariables.
Exercise
You write const assertUserId = (v: string): asserts v is UserId => { if (v === "") throw new Error("empty"); }; and then call assertUserId(x). The compiler reports error 2775. Why, and how do you fix it?
Show answer
An assertion function can only be called through a name with an explicit type annotation, and an arrow function in a const has an inferred type. Either declare it as a function (function assertUserId(v: string): asserts v is UserId { ... }) or annotate the variable: const assertUserId: (v: string) => asserts v is UserId = (v) => { ... };.
Exercise
Write a type predicate isNonEmptyTrimmed(value: unknown): value is NonEmptyTrimmed for a brand NonEmptyTrimmed = Brand<string, "NonEmptyTrimmed">. A value qualifies if it is a string that is not empty and has no leading or trailing whitespace. Then say which input would fool a predicate that only checked value !== "".
Show answer
function isNonEmptyTrimmed(value: unknown): value is NonEmptyTrimmed { return typeof value === "string" && value.length > 0 && value === value.trim(); } A check of only value !== "" would accept " " (whitespace only) and " a " (padded), and it would also accept non-strings such as 5 when the parameter is unknown.