Sub topic 4
A reusable Brand<T, B> helper
This chapter assumes you know TypeScript type aliases, generics, and intersection types. It also assumes you can tell compile-time types from runtime values. You have already seen that string & { readonly __brand: "UserId" } makes a UserId that cannot be passed where an OrderId is required. Here you turn that pattern into one generic helper, Brand<T, B>, and learn why the helper uses a unique symbol as its key.
The cost of writing brands by hand
A hand-written brand repeats the same shape for every type:
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
type Email = string & { readonly __brand: "Email" };
type Cents = number & { readonly __brand: "Cents" };This works, but it has three weaknesses.
- Repetition. The pattern is copied for every brand. A typo in
__brandon one line quietly creates a brand that behaves differently from the others. - Visible key. The property name
__brandis an ordinary string key. It shows up in autocompletion on branded values, and it can collide with a real property of the same name. - Forgeable object brands. If you brand an object type, such as
{ id: number } & { readonly __brand: "Customer" }, an object literal with__brand: "Customer"satisfies it. Any code can write that key by name, so the brand proves nothing about where the value came from.
A generic helper fixes the repetition. A unique symbol key fixes the other two problems.
The helper
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;
type Cents = Brand<number, "Cents">;Each part has a job:
declare const brand: unique symbol;declares a constant whose type is a symbol that is unique to this declaration. Thedeclarekeyword means TypeScript emits no JavaScript for it. The symbol exists only in the type system.Tis the underlying type. It can bestring,number,bigint, an object type, or another branded type.B extends stringis the brand name. It is a string literal type, so"UserId"and"OrderId"are different types.{ readonly [brand]: B }is the tag. Because the key is the unique symbol, no other property can have the same key.
The readonly modifier matters for object types. Without it, a value could be assigned to the tag property type-wise.
How the compiler treats a branded value
A Brand<string, "UserId"> is a subtype of string. It has everything a string has, plus the tag. That gives you two directions of assignability:
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;
declare const userId: UserId;
const asString: string = userId; // OK: a UserId is a string
const upper: string = userId.toUpperCase(); // OK: string methods still work
const plain: string = "u_123";
const bad: UserId = plain; // Error: string lacks the brand
const wrong: OrderId = userId; // Error: the tag types "UserId" and "OrderId" differBranded values flow out to plain types freely, but plain values cannot flow in. The only ways in are a cast or a validating function, which is why the next chapters focus on constructors.
Why a unique symbol and not a string key
The unique symbol version addresses each weakness of __brand.
| Concern | String key `__brand` | `unique symbol` key |
|---|---|---|
| Appears in autocompletion | Yes | No, symbol keys are not suggested after a dot |
| Collides with a real property of the same name | Possible | Not possible |
| Object literal can forge the brand | Yes, write `__brand: "X"` | No, the symbol cannot be named outside its scope |
| Needs `declare` and a constant | No | Yes |
The forge-proof row depends on keeping the symbol private. The symbol is a module-level declaration, and you export only the Brand type. Code in other modules can use Brand<string, "UserId"> but cannot write the tag key, because it cannot reference brand.
Using the helper end to end
The helper does not create values. You still need a place where a plain value becomes branded. Put the cast in one small function per brand:
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type UserId = Brand<string, "UserId">;
type OrderId = Brand<string, "OrderId">;
type Cents = Brand<number, "Cents">;
const userId = (value: string): UserId => value as UserId;
const orderId = (value: string): OrderId => value as OrderId;
const cents = (value: number): Cents => value as Cents;
function loadOrder(id: OrderId): string {
return `loading ${id}`;
}
function charge(user: UserId, amount: Cents): string {
return `charging ${user} ${amount}`;
}
console.log(loadOrder(orderId("o_456")));
console.log(charge(userId("u_123"), cents(1999)));
// loadOrder(userId("u_123")); // Error: UserId is not assignable to OrderId
// charge(cents(1999), userId("u_123")); // Error: arguments in the wrong orderThese constructors do not validate anything. They only label. That is fine for values you already trust, but for input from users or the network you should validate before casting. The next chapter covers that.
The last commented-out call shows a benefit beyond ID mix-ups. Swapped arguments of different brands now fail at compile time, where two plain string and number parameters would also catch some swaps, but two string IDs would not.
Branding something other than a primitive
T can be any type. Branding an object type works the same way:
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type Config = { host: string; port: number };
type ValidatedConfig = Brand<Config, "ValidatedConfig">;
function validate(config: Config): ValidatedConfig {
if (config.port < 1 || config.port > 65535) {
throw new RangeError(`Invalid port: ${config.port}`);
}
return config as ValidatedConfig;
}
function connect(config: ValidatedConfig): string {
return `${config.host}:${config.port}`;
}
console.log(connect(validate({ host: "localhost", port: 8080 })));
// connect({ host: "localhost", port: 8080 }); // Error: missing the brandHere the brand records a fact: this object has passed validate. This use is common because a function can demand proof of validation in its parameter type. This is also where the symbol key helps most. With a string key, { host: "x", port: 1, __brand: "ValidatedConfig" } would pass the type check without validation.
Edge cases and gotchas
The symbol must be declared once. Each declare const brand: unique symbol creates a distinct symbol type. If two files each declare their own brand and define their own Brand, a UserId from one file is not assignable to a UserId from the other, even with the same name. Define Brand in one shared module and import the type everywhere.
Brand names are your responsibility. Two brands with the same B string and the same T are the same type. If two modules both define Brand<string, "Id"> for different concepts, the compiler treats them as interchangeable. Use specific names such as "UserId", not "Id".
The tag does not exist at runtime. Reading userId[brand] is not possible outside the declaring module, and even there the value would be undefined. Do not write code that depends on the brand being present. Logging, JSON.stringify, and equality all see the plain underlying value.
Operations return the plain type. Methods that produce a new value return the unbranded type. For example, userId.toUpperCase() is a string, and a + b on two Cents values is a number. You must re-brand the result if you want the brand to continue. This is correct, since the compiler cannot know that the result still satisfies the brand's meaning.
Constraints on B. B extends string keeps brand names readable in error messages. If you removed the constraint, Brand<string, number> and other odd forms would compile, with no benefit. You could use B extends PropertyKey, but string names are the convention.
What to remember
Brand<T, B>isT & { readonly [brand]: B }, wherebrandis adeclaredunique symbol.- A branded value is assignable to its underlying type, but not the reverse.
- Different brand names on the same underlying type are mutually incompatible.
- Declare the symbol once, export only the
Brandtype, and use specific brand names. - The helper creates no values. You still need constructors, which come next.
Exercise
Two files in a project each contain declare const brand: unique symbol; and type Brand<T, B extends string> = T & { readonly [brand]: B };. Both define type UserId = Brand<string, "UserId">. A function in file A takes a UserId and is called from file B with a UserId made in file B. Will it compile, and what is the fix?
Show answer
It will not compile. Each declare const brand: unique symbol declares a different unique symbol, so the two tag keys differ and the two UserId types are incompatible, despite the same name. The fix is to declare the symbol and Brand once in a shared module, export only the Brand type, and import it in both files.
Exercise
Using the Brand helper, define type Percent = Brand<number, "Percent">. Then explain why the following function fails to compile and how to correct it: function half(p: Percent): Percent { return p / 2; }.
Show answer
The expression p / 2 has type number, because arithmetic on a branded number returns the plain underlying type, and a number is not assignable to Percent. Re-brand the result inside the function: return (p / 2) as Percent;. If the result must also be a valid percentage, do the cast inside a validating constructor instead of at each call site.