Sub topic 14
Deciding when to brand
Earlier chapters showed how to build brands, create them through smart constructors, and where they fail. This chapter covers the remaining question: which values in your codebase deserve a brand, and which do not. It assumes you can write a Brand<T, B> helper, a validating constructor, and a type predicate.
What a brand costs
A brand is not free, even though it disappears at runtime. You pay in four places.
- Construction friction. Every value has to enter the branded type through a constructor or a cast. Tests, fixtures, and scripts all need to do this.
- Reading cost. A newcomer sees
OrderIdand has to find where it is created and what it guarantees. A plainstringneeds no lookup. - Cast surface. Each
as OrderIdis an unchecked claim. The more brands you have, the more casts you write and review. - Arithmetic friction. A branded
numberloses its brand after+,-, orMath.round. You have to re-brand the result.
The cost is mostly a human one. Compile time and bundle size barely change.
What a brand buys
A brand pays off when it does one of two jobs.
- It separates values that look alike but mean different things.
UserIdandOrderIdare both strings. Passing one where the other is expected is a real bug that no test is likely to catch. - It records that a check already happened. An
EmailorPositiveInttells downstream code that validation ran, so that code does not validate again or skip validation by accident.
Ask which job the brand does. If you cannot name one, you probably do not need it.
Where brands pay off
| Situation | Why a brand helps | Suggested tool |
|---|---|---|
| Many ID types that are all strings | Mix-ups compile silently and fail at runtime or corrupt data | Strict brand |
| Values validated at a boundary and used deep inside | The type carries the proof that validation ran | Strict brand with smart constructor |
| Numbers with units (cents vs. dollars, meters vs. seconds) | Unit mix-ups give wrong answers with no error | Strict brand |
| Security-sensitive strings (`SafeHtml`, `SqlFragment`, `Hashed`) | Prevents raw input from reaching a dangerous sink | Strict brand, constructor in one module |
| Internal helpers with one or two string parameters | Mix-ups are visible in a few lines of code | Plain types |
| Display strings such as labels and titles | No invariant, no confusable sibling | Plain types |
| Public API where callers pass literals often | A strict brand forces casts on every caller | Flavor |
Where brands do not help
A brand distinguishes types. It cannot tell two values of the same type apart. This function is a common surprise:
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type AccountId = Brand<string, "AccountId">;
type Cents = Brand<number, "Cents">;
function transfer(from: AccountId, to: AccountId, amount: Cents): void {
console.log(`move ${amount} from ${from} to ${to}`);
}
const alice = "a_1" as AccountId;
const bob = "a_2" as AccountId;
const fee = 250 as Cents;
transfer(bob, alice, fee); // compiles: both arguments are AccountIdThe brand stops you from passing a Cents as an account, but it does nothing about swapped accounts. For that, give the parameters distinct roles with an object argument:
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type AccountId = Brand<string, "AccountId">;
type Cents = Brand<number, "Cents">;
interface TransferRequest {
readonly from: AccountId;
readonly to: AccountId;
readonly amount: Cents;
}
function transfer({ from, to, amount }: TransferRequest): void {
console.log(`move ${amount} from ${from} to ${to}`);
}
transfer({
from: "a_2" as AccountId,
to: "a_1" as AccountId,
amount: 250 as Cents,
});Named properties make a swap visible in code review. This is a better fix than inventing SourceAccountId and TargetAccountId brands.
Brands also give no protection in these cases, covered in the pitfalls chapter:
- Casts and
anyvalues, such as the result ofJSON.parse. - Data that arrives at runtime without passing through a constructor.
- Code in other packages compiled against a different copy of your types.
If your project allows casts freely, brands give a false sense of safety. Treat them as a convention that needs enforcement. A lint rule that forbids as to a branded type outside the constructor module is a good start.
Choosing the strength
You have three levels, from lightest to heaviest.
| Option | Cast needed to create? | Catches ID mix-ups? | Proves validation ran? | Runtime cost |
|---|---|---|---|---|
| Flavor (optional tag) | No | Yes, between flavors | No | None |
| Strict brand | Yes, inside a constructor | Yes | Yes, if only constructors cast | None |
| Wrapper object or class | Yes, to construct | Yes | Yes | An allocation per value, plus unwrapping |
Use these rules of thumb:
- Pick a flavor when the goal is to catch mix-ups and plain values should flow in easily. A flavor cannot prove validation, because a plain
stringis assignable to it. - Pick a strict brand when a value has an invariant, or when a plain value flowing in would be a bug.
- Pick a wrapper when you need runtime identity: methods, a distinct
instanceofcheck, or protection against code that bypasses the type system. You pay in allocations, JSON handling, and.valueaccess everywhere.
A flavor and a strict brand can coexist in one codebase. Flavors suit internal IDs. Strict brands suit validated or security-relevant values.
A decision flow
Adopting brands incrementally
You do not have to brand everything at once. Start where the cost of a bug is highest and the boundary is narrow. A practical order:
- Brand the identifiers of your two or three most-confused entities.
- Put each brand and its constructor in one module and export only the type and the constructor.
- Parse at the edges: HTTP handlers, database rows, environment variables.
- Let the compiler list every call site that now needs a branded value, and fix them from the boundary inward.
A minimal module looks like this:
// ids.ts
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
export type OrderId = Brand<string, "OrderId">;
export type UserId = Brand<string, "UserId">;
export function parseOrderId(raw: string): OrderId {
if (!/^o_[0-9]+$/.test(raw)) {
throw new Error(`Invalid order id: ${raw}`);
}
return raw as OrderId;
}
export function parseUserId(raw: string): UserId {
if (!/^u_[0-9]+$/.test(raw)) {
throw new Error(`Invalid user id: ${raw}`);
}
return raw as UserId;
}The as casts appear only here, directly after the check. Every other file imports the constructors, so a code search for as OrderId returns exactly one hit per brand.
For tests, add a small helper in a test-only module instead of casting in every file:
import { parseOrderId, type OrderId } from "./ids";
export const orderIdFixture = (n: number): OrderId => parseOrderId(`o_${n}`);Using the real constructor in fixtures keeps tests honest, because they fail if the format rule changes.
Warning signs of over-branding
Look for these symptoms when reviewing a codebase.
- Brands that have no constructor and are created only with
as. They name a concept but prove nothing. - Many brands used in only one function. The type adds ceremony without separating anything.
- Frequent
as numberoras stringcasts to strip brands. This means the brand fights the code that uses it. - Brands on values that never cross a module boundary.
If you see these, remove the brand or move it to the boundary where it actually separates concerns.
Summary of the decision
Brand a value when a mix-up or an unvalidated value would cause real harm, when the value crosses module boundaries, and when you can keep creation inside a few constructors. Use flavors when you want mix-up detection without friction. Use wrappers when you need runtime guarantees. Leave everything else as a plain type.
Exercise
A function sendInvoice(customerId: string, invoiceId: string, total: number) is called from many places. Two bugs have shipped: a customerId and invoiceId were swapped, and a total in dollars was passed where cents were expected. Which brands would you add, and what would still go unchecked?
Show answer
Add CustomerId and InvoiceId brands (or flavors) and a Cents brand for the total, each created by a constructor. These prevent both shipped bugs. A brand cannot catch two values of the same brand passed in the wrong order, so if the function took two CustomerId parameters, switch to an object argument with named properties. Casts and unvalidated runtime data (for example an any from JSON.parse) also go unchecked.
Exercise
A teammate brands type PageTitle = Brand<string, "PageTitle"> and creates every value with as PageTitle. What is wrong, and what do you recommend?
Show answer
The brand has no invariant and no confusable sibling, and it has no constructor, so it proves nothing and adds a cast at every use. Recommend a plain string. If titles really need a rule such as a maximum length, add a smart constructor that checks it and keep the cast inside that constructor.
Exercise
When would you choose a wrapper class over a strict brand?
Show answer
Choose a wrapper when you need runtime identity or behavior: methods on the value, instanceof checks, or protection from code that bypasses types. The cost is an allocation per value and unwrapping (for example .value) at use sites, plus extra work to serialize to JSON.