Sub topic 13
Wrapper Objects and Classes as Alternatives
This chapter assumes you have read the earlier chapters on intersection brands, smart constructors, and runtime erasure. You should also be comfortable with discriminated unions and basic class syntax (constructors, private members, static methods).
Brands are not the only way to stop a UserId from being passed where an OrderId is expected. You can also wrap the value in a real object. This chapter covers two wrapper styles, what each one costs at runtime, and how to choose between them and a brand.
The core difference: a brand is a lie, a wrapper is real
An intersection brand such as string & { readonly __brand: "UserId" } is erased at compile time. At runtime the value is a plain string. The tag exists only in the type checker, which is why a cast can forge it and JSON.parse can slip an unchecked value past it.
A wrapper object changes the runtime representation. The value lives inside an object, and the object carries the distinction. Callers cannot pass a raw string where a wrapper is required, and the wrapper cannot be mistaken for any other type, even at runtime.
The price is that every value is now an allocation, and you lose direct use of string or number operations. You must unwrap first.
Style 1: tagged wrapper objects
The simplest wrapper is an object with a literal kind property. This is the same pattern as a discriminated union, applied to identity.
interface UserId {
readonly kind: "UserId";
readonly value: string;
}
interface OrderId {
readonly kind: "OrderId";
readonly value: string;
}
const userId = (value: string): UserId => ({ kind: "UserId", value });
const orderId = (value: string): OrderId => ({ kind: "OrderId", value });
function loadOrder(id: OrderId): void {
console.log("loading", id.value);
}
loadOrder(orderId("o_456"));
loadOrder(userId("u_123")); // Error: Type '"UserId"' is not assignable to type '"OrderId"'.The checker rejects the second call because the kind literals differ. Unlike a brand, the tag is a real property. You can inspect it at runtime with id.kind === "OrderId", which is useful when values of several kinds travel through one untyped channel such as a message queue.
Note that kind is still only a convention. Nothing stops code from writing { kind: "OrderId", value: "" } directly, so validation still needs to live in a constructor function, and the interface alone does not enforce that.
Style 2: classes with private members
Classes can enforce more. TypeScript compares class instance types structurally like everything else, with one exception: when a class has a private, protected, or #private member, only instances declared from that same class declaration are compatible with it. That gives you nominal typing without any tag.
A private constructor closes the last gap. The only way to get an instance is through a static factory that validates.
class UserId {
readonly #value: string;
private constructor(value: string) {
this.#value = value;
}
static of(value: string): UserId {
if (value.length === 0) {
throw new Error("UserId must not be empty");
}
return new UserId(value);
}
equals(other: UserId): boolean {
return this.#value === other.#value;
}
toString(): string {
return this.#value;
}
}
class OrderId {
readonly #value: string;
private constructor(value: string) {
this.#value = value;
}
static of(value: string): OrderId {
if (value.length === 0) {
throw new Error("OrderId must not be empty");
}
return new OrderId(value);
}
toString(): string {
return this.#value;
}
}
function loadOrder(id: OrderId): void {
console.log("loading", id.toString());
}
loadOrder(OrderId.of("o_456"));
loadOrder(UserId.of("u_123")); // Error: the '#value' members come from different declarationsCompare this with the smart constructor pattern from earlier. The validation function and the type are now one unit. There is no cast anywhere, because new UserId(value) is the only place an instance is made, and the compiler blocks new UserId(...) from outside the class.
The trap: classes with only public members are still structural
The nominal behavior comes from the private member, not from the class keyword. Two classes with the same public shape are interchangeable.
class Meters {
constructor(readonly amount: number) {}
}
class Seconds {
constructor(readonly amount: number) {}
}
const distance: Meters = new Seconds(3); // compiles: same public shape
console.log(distance.amount);If you choose classes for safety, always include at least one private or #private field. A class made only of public readonly properties gives you no protection and a false sense of it.
Runtime consequences you must handle
Moving the distinction into a runtime object affects how values behave in equality checks, collections, and serialization. These are the three places where teams get surprised.
Equality
Two wrappers with the same content are different objects. === compares references, so you need an explicit comparison or a canonical key.
class UserId {
readonly #value: string;
private constructor(value: string) {
this.#value = value;
}
static of(value: string): UserId {
return new UserId(value);
}
equals(other: UserId): boolean {
return this.#value === other.#value;
}
toString(): string {
return this.#value;
}
}
const a = UserId.of("u_1");
const b = UserId.of("u_1");
console.log(a === b); // false
console.log(a.equals(b)); // true
const seen = new Set<UserId>([a]);
console.log(seen.has(b)); // false: Set compares by reference
const seenKeys = new Set<string>([a.toString()]);
console.log(seenKeys.has(b.toString())); // trueMap and Set keyed by wrapper objects silently miss matches. Key them by the unwrapped string instead, or intern your wrappers in a cache so one value maps to one object. Brands do not have this problem, because a branded string compares and hashes like any other string.
Serialization
JSON.stringify on a class instance with a #private field produces {}, because private fields are not enumerable properties. With a public value field you get {"value":"u_1"}, which is probably not what your API contract says. Define toJSON() to emit the underlying primitive.
class UserId {
readonly #value: string;
private constructor(value: string) {
this.#value = value;
}
static of(value: string): UserId {
return new UserId(value);
}
toJSON(): string {
return this.#value;
}
}
console.log(JSON.stringify({ id: UserId.of("u_1") })); // {"id":"u_1"}Going the other way, JSON.parse returns plain data, never class instances. You must run the parse step, such as UserId.of(json.id), at every boundary. This is the same boundary discipline as with brands, but here forgetting it is a type error rather than a silent hole, because a raw string is not assignable to UserId.
Cost and ergonomics
Each wrapper is a heap allocation. For a handful of IDs per request this is irrelevant. For millions of numeric values in a hot loop, such as coordinates in a simulation, it adds garbage collection pressure that a branded number avoids entirely.
Wrappers also hide the underlying API. A branded string keeps .length, .startsWith, and template-literal use. A wrapper needs .toString() or an accessor first.
Comparing the three approaches
| Property | Intersection brand | Tagged wrapper object | Class with private member |
|---|---|---|---|
| Runtime representation | Plain primitive | Plain object | Class instance |
| Allocation per value | None | One object | One object |
| Forgeable with a cast | Yes | Yes (object literal) | Only through a cast to `any` or `unknown` |
| Distinction visible at runtime | No | Yes (`kind`) | Yes (`instanceof`) |
| Compare with `===` | Yes | No | No |
| Works as a `Map` key by value | Yes | No | No |
| JSON output | Primitive | Object, unless transformed | `{}` or object, unless `toJSON` is defined |
| Primitive methods usable directly | Yes | No | No |
Choosing between them
Some practical rules follow from the table.
- Choose a brand when values are hashed, sorted, stored in databases, or sent over the wire as primitives, and when allocation cost matters.
- Choose a class when the value has behavior that belongs with it, such as
Money.addthat refuses mixed currencies, or when you needinstanceofto route values at runtime. - Choose a tagged wrapper when data crosses an untyped channel and the receiver must tell kinds apart, or when you want to model several kinds with one discriminated union.
You can also mix them. A common layout keeps IDs as brands, because they are everywhere and must serialize cheaply, and uses classes for a few rich domain values like Money or DateRange.
Exercise
A teammate defines class Meters { constructor(readonly amount: number) {} } and class Seconds { constructor(readonly amount: number) {} }, expecting the compiler to reject const d: Meters = new Seconds(3). It compiles. Explain why, and give two changes that make the two classes distinct.
Show answer
TypeScript compares class instance types by shape, and both classes have only the public property amount: number, so they are structurally identical. Nominal behavior only appears when a class has a private, protected, or #private member. Fix it by adding a #private field to each class (for example readonly #unit = "m" in Meters and readonly #unit = "s" in Seconds), or by adding a private constructor and a static validating factory so each class has its own private member. Alternatively, use a discriminating literal property such as readonly kind = "Meters" and readonly kind = "Seconds", which differ in type.
Exercise
You store UserId class instances as keys in a Set<UserId> and set.has(UserId.of("u_1")) returns false even though an equal ID was added. Why, and what are two ways to fix it?
Show answer
Set compares objects by reference, and UserId.of("u_1") creates a new object each time, so it never matches the stored instance. Fix it by storing the unwrapped string in a Set<string> and checking set.has(id.toString()). You can also intern the instances in a cache so each ID value maps to one shared object. Using a branded string instead of a class also avoids the problem, since strings compare by value.