Sub topic 11
What brands cannot protect you from
This chapter assumes you know how to define a Brand<T, B> helper, write smart constructors, and use type predicates. It covers where brands stop working. A brand is a compile-time label. It makes a promise only as long as every value that carries the label got it honestly.
Brands are erased at runtime
TypeScript removes all types when it compiles to JavaScript. A brand has no runtime representation. The tag property you declared in the type never exists on the value.
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type UserId = Brand<string, "UserId">;
const id = "u_123" as UserId;
console.log(typeof id); // "string"
console.log((id as any)[brand]); // undefined at runtime (and `brand` is only declared)In real code the second console.log would fail, because declare const emits nothing and brand does not exist at runtime. That failure is the point. The brand cannot be inspected, logged, serialized, or checked with typeof or instanceof.
Three consequences follow:
- You cannot test at runtime whether an arbitrary value is a
UserId. Only your validation function can say whether the underlying string is acceptable. JSON.stringifyandJSON.parselose the brand. A branded value written to JSON comes back as a plainstring.- Values that cross a process boundary (HTTP, a database,
postMessage, a file) are plain data on the other side.
Casts bypass every guarantee
A type assertion (as) tells the compiler to trust you. The compiler does not check that the value satisfies the brand, so a cast can attach a brand to anything.
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type Email = Brand<string, "Email">;
const bad = "not-an-email" as Email; // compiles: the cast skips validation
const parsed = JSON.parse('"[email protected]"') as Email; // compiles: JSON.parse returns any, nothing is checkedBoth lines compile. The first brands a string that is not an email. The second takes an any and labels it, so even a valid-looking value was never checked.
The practical rule is to keep casts inside the constructors that do the validation, and nowhere else. Every other file should be unable to create the brand without going through that function.
Casts you may not notice
Casts do not always say as. These also produce unchecked branded values:
- A function that returns
any, such asJSON.parse,Response.json(), or many untyped libraries. If the result is assigned to a branded type, no error is raised. - A generic helper such as
function cast<T>(x: unknown): T, which hides an assertion behind a function call. - Non-null assertions and
// @ts-ignorecomments placed near branded code. - Type-only declarations such as
declare const x: UserId, which promise a value exists without creating one.
You can find these with lint rules. The @typescript-eslint/no-unsafe-assignment and @typescript-eslint/no-unsafe-return rules flag any flowing into typed positions. @typescript-eslint/consistent-type-assertions can restrict as usage.
A brand can lie about its own validity
A brand claims "this value passed check X". Nothing ties the claim to the check. Two situations break the link.
First, the validation can be wrong. If isEmail accepts "[email protected]" and your business rule needs a real top-level domain, every Email is still labeled valid. The type system trusts the predicate.
Second, a type predicate that returns true for the wrong reason is accepted without complaint:
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type PositiveInt = Brand<number, "PositiveInt">;
function isPositiveInt(n: number): n is PositiveInt {
return true; // compiles: TypeScript does not verify the body matches the predicate
}
const x: number = -5;
if (isPositiveInt(x)) {
const safe: PositiveInt = x; // x is now typed PositiveInt, but it is -5
}TypeScript does not check that a predicate body actually tests what its name says. Treat the body of every predicate and assertion function as code that deserves its own unit tests, including the boundary values.
Mutation after branding
A brand describes the value at the moment it was checked. If the underlying value can change afterwards, the brand can become false. Primitives such as strings and numbers are immutable, so this does not affect them. It does affect branded objects and arrays.
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type NonEmptyList = Brand<string[], "NonEmptyList">;
function asNonEmptyList(items: string[]): NonEmptyList {
if (items.length === 0) throw new Error("List must not be empty");
return items as NonEmptyList;
}
const list = asNonEmptyList(["a"]);
list.pop(); // compiles: list is now empty, but still typed NonEmptyListIf you brand a container, also make it readonly (ReadonlyArray<string> or Readonly<...>) so the compiler blocks the mutation, and make a copy when you validate so that the caller's original reference cannot be changed behind your back.
Arithmetic and operations return the base type
Operations on a branded value usually return the unbranded type. The brand does not survive the operation, and nothing re-applies it.
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type PositiveInt = Brand<number, "PositiveInt">;
declare const a: PositiveInt;
declare const b: PositiveInt;
const sum = a + b; // type: number
const diff = a - b; // type: number, and it may be negative
const upper: PositiveInt = a * 2; // Error: number is not assignable to PositiveIntThis failure is the safe direction. The compiler forces you to re-validate. The danger is the opposite habit: writing (a - b) as PositiveInt to silence the error. That cast hides an invariant the operation can violate.
String methods behave the same way. userId.toUpperCase() returns string, so a branded value that is transformed must go back through its constructor.
Branded types and the type system's escape hatches
Brands depend on the compiler seeing the relevant types. Several features let values slip past that check:
| Escape hatch | What happens |
|---|---|
| `any` | Assignable to and from every type, including brands |
| `unknown` narrowed with a cast | The cast replaces validation |
| Overloads and loose function signatures | An overload that accepts `string` can be called with any string |
| Index signatures | `Record<string, T>` keys are plain `string`, so branded keys lose protection |
| Method bivariance | Method parameters are checked loosely, so a method taking `OrderId` may accept `UserId` in some positions |
| Declaration merging and `.d.ts` files | A wrong declaration for a library function can claim it returns a brand |
Object keys are a common surprise. When you iterate with Object.keys or for...in, the keys are always string, even if you built the object from branded keys.
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type UserId = Brand<string, "UserId">;
const names: Record<UserId, string> = {} as Record<UserId, string>;
for (const key of Object.keys(names)) {
// key is string, not UserId
console.log(key);
}If you need branded keys back, use a Map<UserId, string>. A Map keeps the key type through iteration, and it also avoids the string coercion that plain objects apply to keys.
The structural leak with plain strings in unions
A brand made with an intersection is a subtype of its base. A UserId is accepted wherever a string is expected. This is by design, but it means branding protects only one direction:
stringtoUserId: blocked (good).UserIdtostring: allowed.UserIdtoOrderId: blocked (good).
So a function that takes string will happily accept any brand, and it may then use the value as if it were another kind of identifier. If a function is meant to accept only identifiers, give it a union of the brands (UserId | OrderId) or a generic constraint rather than string.
Tests, mocks, and fixtures
Test code is where brands tend to erode. Writing "u_1" as UserId in fifty tests is easy, and it puts casts throughout the codebase. A better approach is a small test helper:
declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };
type UserId = Brand<string, "UserId">;
function parseUserId(value: string): UserId {
if (!/^u_\d+$/.test(value)) {
throw new Error(`Invalid user id: ${value}`);
}
return value as UserId;
}
export const testUserId = (n: number): UserId => parseUserId(`u_${n}`);Fixtures built this way fail loudly when the format rule changes, rather than silently carrying invalid data.
A checklist for auditing a branded codebase
- Search for
as <BrandName>and confirm each hit is inside a constructor, predicate, or test helper. - Search for functions returning
anywhose results feed branded parameters. - Confirm that every predicate and assertion function has tests for valid, invalid, and edge inputs.
- Check that branded objects and arrays are read-only.
- Confirm that data from outside the process passes through a validating constructor before it is typed as a brand.
Summary of limits
| Limit | Cause | Mitigation |
|---|---|---|
| No runtime check | Types are erased | Validate in a constructor |
| Forged brands | `as`, `any`, loose declarations | Lint rules, confine casts |
| Wrong predicate | Compiler does not verify the body | Unit tests |
| Stale brand | Mutable containers | Use readonly types, copy on validation |
| Lost brand | Operations return the base type | Re-validate after each operation |
| Lost keys | `Object.keys` returns `string` | Use `Map` |
Exercise
A teammate writes const total = (a + b) as PositiveInt; where a and b are both PositiveInt. Is this safe, and what would you change?
Show answer
With two positive integers the sum is always positive, so the value is correct here, but the cast is still a bypass and sets a bad precedent. If the code later changes to subtraction, the cast would hide a violated invariant. Move the cast into a function such as addPositive(a: PositiveInt, b: PositiveInt): PositiveInt that documents the reasoning, or pass the result through the validating constructor so the check is re-run.
Exercise
You store a Record<UserId, string> and loop over it with Object.keys. The loop body calls loadUser(key), which requires UserId. Why does this fail to compile, and what are two valid fixes?
Show answer
Object.keys returns string[], so key is a plain string, which is not assignable to UserId. One fix is to pass each key through the validating constructor, for example loadUser(parseUserId(key)). The other is to store the data in a Map<UserId, string> and iterate with for (const [id, name] of map), which keeps the UserId key type.
Exercise
Why does JSON.parse(text) as Email defeat the purpose of branding, and how should the code be written instead?
Show answer
JSON.parse returns any, and the as cast attaches the brand without running any check, so an invalid string gets the Email label. Parse into unknown, then pass the value through a validating function such as parseEmail that checks typeof value === "string" and the email rules before returning the branded type.