Sub topic 14
Deciding When to Brand
Assume you know TypeScript type aliases, intersection types, generics, and the difference between compile-time types and runtime values. This chapter focuses on the design decision: when does a brand prevent a useful class of bugs, and when does it add unnecessary work?
What a brand is buying you
TypeScript uses structural typing. It usually asks whether two values have compatible shapes, not whether they represent the same domain concept. A brand adds a type-level tag so that values with the same runtime representation become different at compile time.
declare const brand: unique symbol;
type Brand<T, Name extends string> = T & {
readonly [brand]: Name;
};
type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;
function findOrder(id: OrderId): void {
console.log("finding order", id);
}
declare const userId: UserId;
declare const orderId: OrderId;
findOrder(orderId); // OK
findOrder(userId); // ErrorThe tag does not exist in the emitted JavaScript. It only makes invalid combinations fail during type checking.
A brand is worth considering when all of these conditions apply:
- Two values have the same base type but different meanings.
- Mixing them would cause a real bug.
- The values cross enough functions or modules that parameter naming is not sufficient.
- You can establish the brand at a trusted validation point.
Common examples include database IDs, URLs, email addresses, currency amounts, measurement units, and validated configuration values.
Compare the alternatives
Branding is not the only way to represent a domain concept. Choose the smallest tool that prevents the failure you care about.
| Approach | Compile-time separation | Runtime representation | Best fit |
|---|---|---|---|
| Plain alias | No | Primitive | Values whose meanings cannot be confused |
| Strict brand | Yes | Primitive | Many functions use interchangeable primitive values |
| Flavored type | Partial | Primitive | Gradual adoption or compatibility with raw input |
| Wrapper object or class | Yes | Object | Runtime behavior or stronger construction rules |
A strict brand makes raw values unusable without a constructor or assertion. That is useful in a mature boundary such as a database adapter, but it can feel inconvenient in a small script.
A flavored type uses an optional tag. A plain string can enter the type, but two flavors remain incompatible:
declare const flavor: unique symbol;
type Flavor<T, Name extends string> = T & {
readonly [flavor]?: Name;
};
type CustomerId = Flavor<string, "CustomerId">;
type ProductId = Flavor<string, "ProductId">;
const raw: string = "c_1";
const customerId: CustomerId = raw; // Allowed
const productId: ProductId = customerId; // ErrorThis is a migration aid, not a validation mechanism. It prevents accidental mixing after values have been typed, but it does not prove that raw is a valid customer ID.
Use a trusted boundary
External data has no TypeScript guarantees. JSON, request bodies, environment variables, and database results must be checked at runtime before they become branded values.
Keep unchecked casts inside constructors or parsing functions:
declare const brand: unique symbol;
type Brand<T, Name extends string> = T & { readonly [brand]: Name };
type UserId = Brand<string, "UserId">;
function parseUserId(value: unknown): UserId {
if (typeof value !== "string" || !/^u_[a-z0-9]+$/.test(value)) {
throw new Error("Invalid user ID");
}
return value as UserId;
}
const id = parseUserId("u_123");This design gives callers a simple contract: a returned UserId passed validation. It does not protect against later misuse of as UserId, stale data, or a programmer who changes the validation rule without updating its callers.
Brand only meaningful boundaries
Do not brand every primitive. A brand adds constructors, validation decisions, and sometimes friction in tests and integrations. Prefer a plain type when swapping two values would be harmless or obvious.
For units and constrained numbers, branding often pays off:
declare const unit: unique symbol;
type Unit<Name extends string> = number & { readonly [unit]: Name };
type Meters = Unit<"Meters">;
type Seconds = Unit<"Seconds">;
const meters = (value: number): Meters => value as Meters;
const seconds = (value: number): Seconds => value as Seconds;
function travel(distance: Meters, duration: Seconds): void {
console.log(distance / duration);
}
travel(meters(100), seconds(20)); // OK
travel(seconds(20), meters(100)); // ErrorArithmetic usually returns a plain number, so domain operations should validate or re-brand their results. For richer behavior, such as unit conversion, invariants, or methods, a class or wrapper object may communicate the model better.
A practical decision rule
Use a strict brand when a value is primitive at runtime, has a distinct domain meaning, and can be validated once at a clear boundary. Use a flavored type when migrating existing code and accepting raw values is important. Use a wrapper when the concept needs runtime identity or behavior. Use no brand when the added separation does not prevent a realistic defect.
Exercise
You receive a validated Meters value and a validated Seconds value. You need conversion methods, unit labels at runtime, and rejection of negative values. Should you use a strict brand or a wrapper object?
Show answer
Use a wrapper object or class. The runtime methods, labels, and invariant checks are requirements that a compile-time-only brand cannot provide.