Sub topic 5
Creating branded values safely with smart constructors
This chapter assumes you can read TypeScript generics and intersection types. It also assumes you know that types are erased at runtime. It builds on the Brand<T, B> helper from the previous chapter. A brand only protects you if values get the brand honestly, and smart constructors are how that happens.
The problem a brand does not solve by itself
A brand is a compile-time label. Nothing stops you from attaching the label to a value that does not deserve it:
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type Email = Brand<string, "Email">;
const oops = "not-an-email" as Email; // compiles, and the type now liesEvery function that accepts an Email will trust that label. The brand is only as reliable as the code that creates branded values. The fix is to put the cast in one place, behind a function that checks the value first.
What a smart constructor is
A smart constructor is a function that takes a raw value, checks it, and returns the branded type. Ordinary constructors build any object you ask for. A smart constructor refuses to build one that breaks the rules.
The working model has three rules:
- Raw values go in and branded values come out.
- The cast (
as) or the type predicate that grants the brand appears only inside the constructor, directly after validation. - Everywhere else in the program, code receives branded values and never creates them.
A throwing constructor
The simplest constructor throws when the input is invalid. This version uses a type predicate to grant the brand, so it contains no as:
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type Email = Brand<string, "Email">;
function isEmail(value: string): value is Email {
return /^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value);
}
function parseEmail(value: string): Email {
if (!isEmail(value)) {
throw new Error(`Invalid email: ${value}`);
}
return value; // narrowed to Email by the predicate
}
function sendWelcome(to: Email): void {
console.log("sending to", to);
}
sendWelcome(parseEmail("[email protected]"));
sendWelcome("[email protected]"); // Error: string is not assignable to EmailThe compiler error on the last line is what you want. It forces every caller through parseEmail. The next chapter covers predicates and assertion functions in detail. Here the point is that the check and the brand are in the same function.
A constructor that returns a result
Throwing suits cases where bad input is a bug. For user input, invalid data is expected, and an exception is a clumsy way to report it. Return a result type instead, so the caller must handle both outcomes:
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type UserId = Brand<string, "UserId">;
type Result<T, E> =
| { ok: true; value: T }
| { ok: false; error: E };
function parseUserId(input: string): Result<UserId, string> {
const trimmed = input.trim();
if (!/^u_[0-9]+$/.test(trimmed)) {
return { ok: false, error: `Invalid user id: ${input}` };
}
return { ok: true, value: trimmed as UserId };
}
const result = parseUserId(" u_123 ");
if (result.ok) {
console.log("valid", result.value); // result.value is UserId
} else {
console.log("rejected", result.error);
}Here the cast is acceptable because it sits on the line after the check, inside the one function that owns the rule. The ok field narrows the union, so result.value exists only on the success branch.
| Style | Use when | Caller must |
|---|---|---|
| Throwing (`parseEmail`) | Invalid input means a programming error, or a layer above already catches errors | Wrap in `try`/`catch` if failure is possible |
| Result (`parseUserId`) | Invalid input is routine, such as form fields or request bodies | Check `ok` before reading `value` |
You can offer both. Write the result version first, then build the throwing one on top of it.
Normalizing as well as validating
A smart constructor can also change the value, so every branded value is in one canonical form:
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type Email = Brand<string, "Email">;
function parseEmail(input: string): Email {
const normalized = input.trim().toLowerCase();
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(normalized)) {
throw new Error(`Invalid email: ${input}`);
}
return normalized as Email;
}
const a = parseEmail(" [email protected] ");
const b = parseEmail("[email protected]");
console.log(a === b); // trueNormalizing means two Email values compare equal with === whenever they refer to the same address. Without it, the brand would only promise "this string looked like an email once".
Keeping the cast inside one module
A convention is stronger when the language helps enforce it. Put each brand and its constructor in one module, and export only what callers need:
// email.ts
declare const brand: unique symbol;
export type Email = string & { readonly [brand]: "Email" };
export function parseEmail(input: string): Email {
const normalized = input.trim().toLowerCase();
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(normalized)) {
throw new Error(`Invalid email: ${input}`);
}
return normalized as Email;
}The brand symbol is not exported, so other modules cannot write the brand's structure by hand. They can use the Email type but cannot build a value of it without parseEmail. This helps, but it is not airtight. Any file can still write x as Email. To close that gap, add a lint rule that bans as Email outside email.ts. ESLint's no-restricted-syntax can do this.
Common errors
- Casting at the call site. Writing
parseEmail(x)in some places andx as Emailin others defeats the design. Treat every cast outside a constructor as a bug. - Losing the brand through string methods. Methods such as
toLowerCase()andtrim()return plainstring, so the result is no longer anEmail:
```typescript declare const brand: unique symbol; type Email = string & { readonly [brand]: "Email" }; declare const email: Email;
const upper = email.toUpperCase(); // type is string const again: Email = upper; // Error: string is not assignable to Email ```
This is correct behavior. The new string has not been validated. Run it back through the constructor if you need an Email again.
- Validating weaker than the brand claims. If the brand is
PositiveIntbut the check isn >= 0, zero gets through. The brand name is a promise, so the check must enforce all of it. - Checking in one place and mutating later. Brands on primitives are safe because primitives are immutable. A branded object or array is different. Someone can mutate it after validation and break the rule the brand stands for. Prefer
readonlytypes for branded objects. - Swallowing failures. A constructor that returns a default (such as an empty string cast to
Email) on bad input brings back the original problem. Fail loudly or return a result.
Testing the constructor
Because the constructor is the only gate, it is the one function worth testing thoroughly. Cover valid input, each rejection rule, and normalization. A short check with Node's built-in assertions:
import assert from "node:assert/strict";
declare const brand: unique symbol;
type Email = string & { readonly [brand]: "Email" };
function parseEmail(input: string): Email {
const normalized = input.trim().toLowerCase();
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(normalized)) {
throw new Error(`Invalid email: ${input}`);
}
return normalized as Email;
}
assert.equal(parseEmail(" [email protected] "), "[email protected]");
assert.throws(() => parseEmail("no-at-sign"));
assert.throws(() => parseEmail("a@b"));
assert.throws(() => parseEmail(""));
console.log("all checks passed");Types cannot test your regular expression. They only guarantee that code which holds an Email came through this function.
Summary of the pattern
- Define the brand type.
- Write one constructor per brand that validates, optionally normalizes, and grants the brand.
- Keep the grant (cast or predicate) inside that constructor, preferably in its own module.
- Make every other function accept the branded type, so the compiler routes all raw values through the constructor.
Exercise
A teammate writes const id = req.query.id as UserId; in a request handler, although parseUserId exists. What goes wrong, and how should the line change?
Show answer
The cast tells the compiler the value is a valid UserId without running any check, so malformed or missing input flows into code that trusts the brand. Replace it with a call to parseUserId(String(req.query.id)) (or the throwing variant), and handle the failure case, for example by returning a 400 response.
Exercise
Write a smart constructor parsePort(n: number) for a Port brand that accepts only integers from 1 to 65535 and throws a RangeError otherwise. Why does port + 1 not have type Port?
Show answer
declare const brand: unique symbol; type Port = number & { readonly [brand]: "Port" }; function parsePort(n: number): Port { if (!Number.isInteger(n) || n < 1 || n > 65535) { throw new RangeError(Invalid port: ${n}); } return n as Port; }. The expression port + 1 has type number, because arithmetic operators return plain numbers. The result might be 65536, which is not a valid port, so it must go through parsePort again.