Sub topic 13
Wrapper Objects and Classes as Alternatives
This chapter assumes basic TypeScript syntax, generics, intersection types, and the difference between compile-time types and runtime values. So far, brands have added compile-time labels to ordinary strings and numbers. Wrapper objects and classes solve the same domain-confusion problem by creating real runtime values.
Wrapper objects
A wrapper object stores a primitive value inside an object. Its shape can include methods and a distinguishing property.
type UserId = {
readonly value: string;
readonly kind: "UserId";
};
type OrderId = {
readonly value: string;
readonly kind: "OrderId";
};
function userId(value: string): UserId {
if (!/^u_[0-9]+$/.test(value)) {
throw new Error("Invalid user ID");
}
return { value, kind: "UserId" };
}
function orderId(value: string): OrderId {
if (!/^o_[0-9]+$/.test(value)) {
throw new Error("Invalid order ID");
}
return { value, kind: "OrderId" };
}
function loadOrder(id: OrderId): void {
console.log(`Loading order ${id.value}`);
}
const order = orderId("o_123");
loadOrder(order);
// loadOrder(userId("u_456")); // Type errorThe kind property is a runtime tag. Unlike a brand based on a unique symbol, other code can inspect it. This helps when values cross a JavaScript boundary or need runtime serialization.
Wrapper objects have costs:
- They use more memory than primitive strings.
- Callers must access
.value. - Equality compares object identity, so two wrappers containing
"u_123"are different objects. - JSON serialization includes the wrapper shape.
| Approach | Runtime object | Runtime validation | Works as a primitive directly |
|---|---|---|---|
| Branded string | No | Only if you add it | Yes |
| Tagged wrapper | Yes | Easy to add | No |
| Class instance | Yes | Easy to centralize | No |
Classes with private construction
A class can hide its constructor and expose a parsing method. This creates a single place where the invariant is checked.
class EmailAddress {
private constructor(
public readonly value: string,
) {}
static parse(value: string): EmailAddress {
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value)) {
throw new Error(`Invalid email address: ${value}`);
}
return new EmailAddress(value);
}
domain(): string {
return this.value.slice(this.value.indexOf("@") + 1);
}
toString(): string {
return this.value;
}
}
function sendWelcomeEmail(to: EmailAddress): void {
console.log(`Sending welcome email to ${to}`);
}
const email = EmailAddress.parse("[email protected]");
sendWelcomeEmail(email);
console.log(email.domain());
// EmailAddress.parse("invalid"); // Throws at runtime
// sendWelcomeEmail("[email protected]"); // Type errorThe private constructor prevents callers from creating an instance without validation. The class also gives the value behavior, such as domain().
A class is useful when the concept has operations, identity, or a stable runtime representation. A wrapper object is often simpler when the value only needs a tag and a field. A brand is usually the lightest choice when the value should remain a normal primitive and validation happens elsewhere.
Choosing an alternative
Use a wrapper or class when:
- Runtime code must recognize the value.
- The value has domain methods.
- You want to control serialization.
- You need one central construction API.
Use a brand when:
- Primitive operations should remain convenient.
- Runtime allocation matters.
- The distinction mainly protects function parameters.
- Validation already occurs at an input boundary.
A class can also add unnecessary ceremony. For a simple UserId, a branded string with a validating parser is often easier to pass through APIs. For a Money value with currency rules and arithmetic methods, a class or wrapper usually communicates the model better.
Exercise
Which representation is usually the best fit for a value that must expose methods such as add, subtract, and convertCurrency?
Show answer
A class or wrapper object, because it can keep the value and its domain operations together at runtime.