Sub topic 3
Your first branded type
This chapter builds a branded type from scratch using an intersection with a tag object. It assumes you know TypeScript type aliases, functions, generics, intersection and union types, and the difference between compile-time types and runtime values. Earlier chapters showed that two aliases of string are interchangeable. Here you make them distinct.
The idea in one sentence
A branded type is an existing type, such as string, intersected with an object type that carries a tag. The tag exists only in the type system. Two types with different tags are no longer compatible, so the compiler rejects one where the other is expected.
Recap of the problem
Here is the failing case from the previous chapter.
type UserId = string;
type OrderId = string;
function loadOrder(id: OrderId): void {
console.log("loading", id);
}
const userId: UserId = "u_123";
loadOrder(userId); // compiles: both aliases are just stringAn alias is only another name for a type. UserId and OrderId both mean string, so the compiler has no way to tell them apart. We need two types that differ in shape.
Giving the types different shapes
TypeScript compares types by shape. If we cannot make the underlying values differ, we can make the types differ. An intersection A & B is a type that has everything in A and everything in B. If we intersect string with an object type that has a property __brand, the result is a string that also carries that property, as far as the compiler is concerned.
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
function loadOrder(id: OrderId): void {
console.log("loading", id);
}
const userId = "u_123" as UserId;
const orderId = "o_456" as OrderId;
loadOrder(orderId);
loadOrder(userId); // Error: Type 'UserId' is not assignable to type 'OrderId'.The two tags use different string literal types: "UserId" and "OrderId". A property cannot have both types at once, so neither type is assignable to the other. The call loadOrder(userId) fails to compile.
Reading the definition piece by piece
| Part | Meaning |
|---|---|
| `string` | The underlying type. Every string operation still works. |
| `&` | Intersection. The value must satisfy both sides. |
| `{ readonly __brand: "UserId" }` | The brand. An object type with one property whose type is a literal. |
| `readonly` | Signals that the tag is not meant to be changed. |
| `"UserId"` | The literal that makes this brand different from every other brand. |
The property name __brand is a convention. Any name works as long as the same name is used for all your brands and the literal values differ.
Why the intersection is still usable as a string
A branded value is still a string from the compiler's point of view, because string & { ... } is assignable to string. You can use string methods, template literals, and comparisons without any conversion.
type UserId = string & { readonly __brand: "UserId" };
const userId = "u_123" as UserId;
const upper: string = userId.toUpperCase();
const length: number = userId.length;
const message: string = `user ${userId}`;
const plain: string = userId; // widening to string is allowed
console.log(upper, length, message, plain);The assignment goes only one way. A branded type can flow into a plain string, but a plain string cannot flow into a branded type. That one-way rule is what makes the technique useful.
type UserId = string & { readonly __brand: "UserId" };
function greet(id: UserId): string {
return `hello ${id}`;
}
const raw: string = "u_123";
greet(raw); // Error: Type 'string' is not assignable to type 'UserId'.The brand does not exist at runtime
This is the most important fact about the technique. The tag is a lie that the compiler agrees to believe. At runtime, "u_123" as UserId is just the string "u_123". It has no __brand property. TypeScript erases all types when it compiles to JavaScript, and the cast is erased with them.
type UserId = string & { readonly __brand: "UserId" };
const userId = "u_123" as UserId;
console.log(typeof userId); // "string"
console.log((userId as any).__brand); // undefined
console.log(JSON.stringify({ id: userId })); // {"id":"u_123"}This has two consequences.
- Branding costs nothing at runtime. There is no wrapper object, no extra memory, and no change to how the value serializes.
- The compiler cannot prove that a value really has the meaning its brand claims. Whoever writes
as UserIdis making a promise.
Why the `as` cast is needed
A plain string literal is not assignable to a branded type, so you must use a type assertion to create the first branded value. An assertion tells the compiler "trust me about this type."
type UserId = string & { readonly __brand: "UserId" };
const a: UserId = "u_123"; // Error: Type 'string' is not assignable to type 'UserId'.
const b = "u_123" as UserId; // OK: the assertion creates the brandThe assertion is allowed because string and string & { ... } overlap sufficiently. TypeScript permits a cast when one type is assignable to the other in at least one direction. Here UserId is assignable to string, so the cast compiles.
Scattering as UserId through a codebase defeats the purpose. Every cast is an unchecked claim. Later chapters move the cast into a single function that validates its input first, so the rest of the program never needs one. For now, treat the cast as the place where a brand is created and keep the number of such places small.
type UserId = string & { readonly __brand: "UserId" };
// The only place in this file that creates a UserId.
function toUserId(value: string): UserId {
return value as UserId;
}
const id = toUserId("u_123");
console.log(id);This function does no checking yet, but it already gives you one named place to add checks later.
How the compiler decides
When you pass userId to a parameter of type OrderId, the compiler checks that UserId is assignable to OrderId. An intersection is assignable to a target only if some part of it satisfies each requirement of the target. The target requires a __brand property of type "OrderId". The source has __brand of type "UserId". The literal types do not match, so the check fails.
flowchart TDThe diagram below shows the same decision as a flow.
Common mistakes
Using the same literal for two brands
If two brands share a tag, they are the same type again.
type UserId = string & { readonly __brand: "Id" };
type OrderId = string & { readonly __brand: "Id" };
function loadOrder(id: OrderId): void {
console.log("loading", id);
}
const userId = "u_123" as UserId;
loadOrder(userId); // compiles: both brands are "Id"Copying and pasting a brand definition and forgetting to change the literal is the usual cause. The next chapter removes this risk with a reusable helper.
Forgetting that the cast is unchecked
Nothing stops you from branding a value that does not fit.
type UserId = string & { readonly __brand: "UserId" };
const nonsense = "" as UserId; // compiles, but an empty string is not a real IDThe type system records which kind of value you have. It does not record whether the value is valid. Validation is the job of the constructors covered later in this tutorial.
Expecting the brand to appear in output
Because the brand is erased, it cannot be inspected, logged, or checked with typeof or in. Code like if ("__brand" in value) will not detect a brand and will usually be false.
Using a plain object type as the brand
Writing the brand as an optional property or as a wider type changes the behavior. An optional tag, for example, lets plain strings flow in without a cast. That is a deliberate variation called flavoring, covered in a later chapter. For a strict brand, the tag must be required.
Putting it together
The following program defines two brands, creates values through one function each, and shows which calls the compiler accepts.
type UserId = string & { readonly __brand: "UserId" };
type OrderId = string & { readonly __brand: "OrderId" };
const toUserId = (value: string): UserId => value as UserId;
const toOrderId = (value: string): OrderId => value as OrderId;
interface Order {
id: OrderId;
buyer: UserId;
}
function describe(order: Order): string {
return `order ${order.id} bought by ${order.buyer}`;
}
const order: Order = {
id: toOrderId("o_456"),
buyer: toUserId("u_123"),
};
console.log(describe(order));
// Swapped fields are now a compile error:
// const broken: Order = { id: toUserId("u_123"), buyer: toOrderId("o_456") };If you uncomment the last line, the compiler reports two errors, one for each swapped field. This is the kind of mix-up that plain string fields would let through.
Summary of behavior
| Operation | Allowed? | Reason |
|---|---|---|
| Branded to `string` | Yes | The intersection is assignable to each of its parts. |
| `string` to branded | No | The plain string has no `__brand` property. |
| `UserId` to `OrderId` | No | The `__brand` literals differ. |
| `"x" as UserId` | Yes | A cast is allowed, but it is unchecked. |
| String methods on a branded value | Yes | It is still a string. |
Exercise
Given type A = string & { readonly __brand: "A" } and type B = string & { readonly __brand: "B" }, which of these lines fail to compile: (1) const x: A = "hi"; (2) const y = "hi" as A; (3) const z: string = y; (4) const w: B = y;
Show answer
Lines (1) and (4) fail. Line (1) fails because a plain string literal has no brand property, so it is not assignable to A. Line (4) fails because the brand literal "A" is not assignable to "B". Line (2) compiles because a type assertion is allowed between string and A. Line (3) compiles because a branded value is assignable to its underlying type string.
Exercise
Why does JSON.stringify({ id: "u_123" as UserId }) produce the same output as it would for a plain string, and what does this tell you about branded types?
Show answer
The brand is erased when TypeScript compiles to JavaScript, so the value at runtime is an ordinary string with no extra property. This shows that branding adds no runtime cost or change in serialization, and also that the brand cannot be detected at runtime.