Sub topic 10
Composing and refining brands
This chapter assumes you can write a generic Brand<T, B> helper, use a unique symbol as the tag key, and write a smart constructor. It also assumes you know how intersection types combine properties. Here you will make brands stackable, so that one brand refines another, and you will see where stacking breaks.
Why a refinement relationship is useful
Many domain values come in stages. An email address is a string that passed a format check. A verified email is an email address the user also confirmed by clicking a link. Code that sends a newsletter needs the second stage. Code that writes a log line needs only the first.
You want these rules:
- A
VerifiedEmailcan be used wherever anEmailis expected. - An
Emailcannot be used where aVerifiedEmailis expected. - Neither one mixes with an arbitrary
stringthat has not been validated.
That is a subtype relationship, which TypeScript already models well. You have to build the brand so it produces that relationship.
Why a single string tag cannot stack
The simple form from earlier chapters stores the brand name as one literal type:
declare const brand: unique symbol;
type SingleBrand<T, B extends string> = T & { readonly [brand]: B };
type Email = SingleBrand<string, "Email">;
type VerifiedEmail = SingleBrand<Email, "Verified">;VerifiedEmail expands to string & { [brand]: "Email" } & { [brand]: "Verified" }. The property [brand] now has the type "Email" & "Verified", which is never. Because the property is a literal-typed discriminant, TypeScript reduces the whole intersection to never. No value can have that type, and every assignment to it fails.
The tag therefore has to be something that intersects cleanly. A set of names stored as object keys does that.
Brands stored as object keys
Make the tag an object whose keys are the brand names:
declare const brands: unique symbol;
type Brand<T, B extends string> = T & {
readonly [brands]: { readonly [K in B]: true };
};
type Email = Brand<string, "Email">;
type VerifiedEmail = Brand<Email, "Verified">;Now VerifiedEmail expands to:
string
& { [brands]: { Email: true } }
& { [brands]: { Verified: true } }When intersected object types share a property, the property type is the intersection of the two. So [brands] has the type { Email: true } & { Verified: true }, an object with both keys. Nothing collapses.
Assignability follows from this. A VerifiedEmail has every member an Email requires, so it is assignable to Email. An Email lacks the Verified key, so it is not assignable to VerifiedEmail.
declare const brands: unique symbol;
type Brand<T, B extends string> = T & {
readonly [brands]: { readonly [K in B]: true };
};
type Email = Brand<string, "Email">;
type VerifiedEmail = Brand<Email, "Verified">;
declare function sendNewsletter(to: VerifiedEmail): void;
declare function logEmail(to: Email): void;
declare const verified: VerifiedEmail;
declare const unverified: Email;
logEmail(verified); // OK: a VerifiedEmail is also an Email
sendNewsletter(verified); // OK
sendNewsletter(unverified); // Error: missing the "Verified" brandRefining through a constructor
Each step up the chain needs its own smart constructor. The second constructor takes the already-branded Email, so a raw string cannot skip the first check.
declare const brands: unique symbol;
type Brand<T, B extends string> = T & {
readonly [brands]: { readonly [K in B]: true };
};
type Email = Brand<string, "Email">;
type VerifiedEmail = Brand<Email, "Verified">;
function parseEmail(value: string): Email {
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value)) {
throw new Error(`Invalid email: ${value}`);
}
return value as Email;
}
const confirmedAddresses = new Set<string>(["[email protected]"]);
function markVerified(email: Email): VerifiedEmail | null {
return confirmedAddresses.has(email) ? (email as VerifiedEmail) : null;
}
const email = parseEmail("[email protected]");
const verified = markVerified(email);
if (verified !== null) {
console.log("sending to", verified);
}Two details are worth noting:
markVerifiedacceptsEmail, notstring. The first brand is a precondition for the second.- It returns
VerifiedEmail | nullinstead of throwing. Failing to verify is an expected outcome, so a nullable result suits it better than an exception. Choose per brand whether failure is routine or exceptional.
The cast email as VerifiedEmail is legal because VerifiedEmail is a subtype of Email, and TypeScript permits assertions between related types. Keep that cast inside the constructor, as in earlier chapters.
Independent brands combined by intersection
Refinement is a chain. Sometimes you want independent properties with no natural order, such as "is an integer" and "is positive". Define each brand separately and intersect them:
declare const brands: unique symbol;
type Brand<T, B extends string> = T & {
readonly [brands]: { readonly [K in B]: true };
};
type Int = Brand<number, "Int">;
type Positive = Brand<number, "Positive">;
type PositiveInt = Int & Positive;
function isInt(n: number): n is Int {
return Number.isInteger(n);
}
function isPositive(n: number): n is Positive {
return n > 0;
}
function pageCount(total: PositiveInt, perPage: PositiveInt): number {
return Math.ceil(total / perPage);
}
function paginate(total: number, perPage: number): number {
if (isInt(total) && isPositive(total) && isInt(perPage) && isPositive(perPage)) {
return pageCount(total, perPage);
}
throw new RangeError("Both values must be positive integers");
}After isInt(total) succeeds, total has the type Int. The second guard narrows it again, and because neither type is a subtype of the other, TypeScript gives it the intersection Int & Positive. That is exactly PositiveInt.
The practical benefit is reuse. A function that needs only an integer, such as an array index, accepts Int. A function that needs only a positive number accepts Positive. A PositiveInt satisfies both.
Order does not matter for intersections. Int & Positive and Positive & Int are the same type. For a refinement chain, order carries meaning only through the constructors you write, because Verified is created from Email.
Which direction is free
| Conversion | Example | Allowed without a cast? |
|---|---|---|
| More specific to less specific | `VerifiedEmail` to `Email` | Yes |
| Branded to its base type | `Email` to `string` | Yes |
| Less specific to more specific | `Email` to `VerifiedEmail` | No, needs a checking function |
| Base type to branded | `string` to `Email` | No, needs a checking function |
| Sideways between unrelated brands | `UserId` to `OrderId` | No |
The rule is that widening costs nothing and narrowing requires evidence. Every narrowing step should map to a runtime check, which is why each constructor is worth its own function.
Common errors
- Using a single literal tag and stacking it. The result is
never, and the error messages are confusing because the type name looks fine. Use the object-key form whenever brands might be composed. - Casting past a level. Writing
raw as VerifiedEmailfrom a plainstringcompiles, becausestringis also a base ofVerifiedEmail. It skips both checks. Search foras VerifiedEmailin review. It should appear only inmarkVerified. - Repeating a brand name.
Brand<Email, "Email">adds the keyEmaila second time. This is harmless, since it intersects with itself, but it signals a design mistake. - Piling on brands. A type like
Brand<Brand<Brand<string, "A">, "B">, "C">prints a long structure in error messages and is hard to read. If you need more than two or three layers, name each intermediate alias and check that each layer maps to a distinct runtime check. - Expecting a union of names.
Brand<string, "A" | "B">produces an object with both keys required, so it means "A and B". It does not mean "A or B". To accept either, writeBrand<string, "A"> | Brand<string, "B">.
Summary of the design choices
- Store brand names as keys of an object tag, not as one literal, if you want brands to compose.
- Use a chain (
Brand<Email, "Verified">) when one property depends on another. Use an intersection (Int & Positive) when the properties are independent. - Give each narrowing step its own constructor or type guard, taking the previous brand as input where the order matters.
- Keep casts inside those constructors.
Exercise
Given type Brand<T, B extends string> = T & { readonly [brands]: { readonly [K in B]: true } }; and type Id = Brand<string, "Id">;, define type AdminId = Brand<Id, "Admin">. Then say whether each call compiles, with declare function deleteUser(by: AdminId): void;, declare function viewProfile(by: Id): void;, declare const admin: AdminId; and declare const plain: Id;: (a) viewProfile(admin), (b) deleteUser(plain), (c) deleteUser("u_1").
Show answer
(a) compiles, because AdminId has the Id key plus the Admin key, so it is assignable to Id. (b) fails, because plain lacks the Admin key. (c) fails, because a plain string literal has neither tag. The only legitimate way to get an AdminId is a function that checks admin rights and then performs the cast internally.
Exercise
A teammate writes type Even = Brand<number, "Even">, type Small = Brand<number, "Small">, and then const n = 4 as Even & Small; in a function that also receives a raw number from user input. What is wrong with this design, and how would you fix it?
Show answer
The cast 4 as Even & Small asserts both properties without any check, so nothing stops the same cast from being applied to arbitrary input. Fix it by writing type guards isEven(n: number): n is Even and isSmall(n: number): n is Small that perform the real checks, then narrowing the input with both guards so it becomes Even & Small only after both pass.