In Zod 4, what does .brand<"UserId">() change about a schema's inferred type and parse result, and how does that keep UserId and OrderId apart?
answer
- structural typing, simulated nominal
- intersection with z.$brand
- static only, value unchanged
- output branded by default
- parse is the only mint
basics
~20 sIt intersects the schema's output type with z.$brand<"UserId">, so short of a cast, only values returned by that schema's parse fit a UserId parameter, and an OrderId does not. The runtime value stays a plain string, and by default the input type is unbranded.
solid answer
~40 s`.brand<"UserId">()` makes the inferred output type `string & z.$brand<"UserId">`. A plain string lacks the brand member and an `OrderId` carries a different one, so `cancelOrder(id: OrderId)` rejects both at compile time; the only cast-free way to get the branded type is the schema's `.parse()`. Branding is static only: the parsed value is the same string, and `parse` never checks the brand, so any valid UUID parses as either id. By default only the output side is branded, so callers pass ordinary strings in; since Zod 4.2 a second generic, `"in"` or `"inout"`, moves or extends the brand. A branded id is still assignable to `string`, and it loses its brand across JSON, so the receiver parses again.
code
typescript · 20 linesimport * as z from "zod";
const UserId = z.uuid().brand<"UserId">();
const OrderId = z.uuid().brand<"OrderId">();
type UserId = z.infer<typeof UserId>;
type OrderId = z.infer<typeof OrderId>;
function cancelOrder(id: OrderId): void {
console.log(`cancelling ${id}`);
}
const userId = UserId.parse("3f1c2a9e-5b7d-4e2a-9c1f-8d6b4a2e7c10");
// cancelOrder(userId); // compile error: UserId is not assignable to OrderId
// cancelOrder("3f1c2a9e-5b7d-4e2a-9c1f-8d6b4a2e7c10"); // compile error: plain string
cancelOrder(OrderId.parse("3f1c2a9e-5b7d-4e2a-9c1f-8d6b4a2e7c10")); // ok
console.log(typeof userId); // "string"
console.log(JSON.stringify({ userId })); // the plain UUID stringgo deeper
Recall that .brand<"Name">() makes two otherwise identical string types incompatible, and that parse is how you obtain a branded value.
Explain the intersection with z.$brand, that only the output side is branded by default, and that the runtime value is unchanged.
Show where brands stop helping: parse never checks the brand, JSON strips the guarantee, and fixtures need parsing or a contained cast.
Weigh branding every entity id across a codebase: fewer mixed-id bugs against parsing at every boundary and friction in tests and tooling.
## What `.brand()` does to the type TypeScript compares object and primitive types **structurally**: two aliases of `string` are interchangeable, so a function that takes an order id will accept a user id without complaint. Zod's `.brand()` simulates **nominal typing** on top of a schema: ```ts import * as z from "zod"; const UserId = z.uuid().brand<"UserId">(); const OrderId = z.uuid().brand<"OrderId">(); type UserId = z.infer<typeof UserId>; // string & z.$brand<"UserId"> type OrderId = z.infer<typeof OrderId>; // string & z.$brand<"OrderId"> ``` The brand is an **intersection** with `z.$brand<"UserId">`, a type keyed by a unique symbol. A plain `string` lacks that member, and a `UserId` carries a different brand than an `OrderId`, so neither is assignable to `OrderId`. The only way to get a value of that type without a cast is to **run it through the schema**: `OrderId.parse(raw)` returns the branded type. ## What it does not do at runtime Branding is **static only**. The Zod docs state that branded types do not affect the runtime result of `.parse`. - The parsed value is the same plain string; `typeof` reports `"string"` and `JSON.stringify` writes it unchanged. - `.parse()` does not check the brand name. Both schemas above accept any valid UUID, so an order id string parses happily as a `UserId`. The brand guards **compile-time flow**, not data provenance. - A branded value is still assignable to `string`, because the intersection only adds a member. Code that wants any string keeps working. ## Direction: output by default By default only the **output** type is branded; the input stays plain: | Call | `z.input` | `z.output` | |---|---|---| | `z.string().brand<"USD">()` | `string` | `string & z.$brand<"USD">` | | `z.string().brand<"USD", "in">()` | `string & z.$brand<"USD">` | `string` | | `z.string().brand<"USD", "inout">()` | branded | branded | The second generic (`"out"`, `"in"` or `"inout"`) arrived in **Zod 4.2**. Output-only branding is what you normally want: callers pass ordinary strings to `parse`, and only what comes out is trusted. One more detail from the signature: `.brand()` called **without** a type argument returns the schema type unchanged, so it creates no distinct brand at all. ## Branding object schemas too Brands are not limited to strings. Two object schemas with identical fields are interchangeable to TypeScript, and a brand separates them in the same way: ```ts const Cat = z.object({ name: z.string() }).brand<"Cat">(); const Dog = z.object({ name: z.string() }).brand<"Dog">(); const pluto = Dog.parse({ name: "pluto" }); const simba: z.infer<typeof Cat> = pluto; // compile error: a Dog is not a Cat ``` This is useful when one plain shape means different things in different places, such as a validated address versus an address typed in by a user, and only the validated one may reach a function that ships parcels. The rule is the same as for ids: an object literal written by hand is not assignable to the branded type, so the only cast-free path is the schema's `parse`. ## Keeping ids apart in practice 1. Define one branded schema per id kind: `UserId`, `OrderId`. 2. Derive the types with `z.infer`, and use them in every signature that takes an id: `cancelOrder(id: OrderId)`. 3. Use the branded schemas inside the entity schemas too (`z.object({ id: OrderId, ownerId: UserId })`), so parsing an order yields branded ids. 4. Parse at the boundary where ids enter: request parameters, stored rows, message payloads. After that, the compiler rejects `cancelOrder(userId)`. ## Costs and edges - **Test fixtures** need branded values: parse them through the schema, or confine an `as OrderId` cast to a test helper. - **Serialisation strips nothing visible but loses the guarantee**: a branded id sent as JSON arrives as a plain string and must be parsed again to be branded on the other side. - **Brands compose** with wrappers: `z.uuid().brand<"UserId">().optional()` infers `(string & z.$brand<"UserId">) | undefined`. - **Zod 4 internals**: Zod 3 had a dedicated `ZodBranded` class; Zod 4 drops it and modifies the inferred type directly, with the same user-facing `.brand()` API. - The general TypeScript technique of hand-rolled brands and why a cast-based brand needs a trusted constructor is covered in the TypeScript material on nominal types; with Zod, the schema's `parse` is that trusted constructor.
- A branded UserId is sent to another service as JSON. Is it still branded on arrival?No. The brand never existed at runtime, so `JSON.stringify` writes the plain UUID and the receiver gets a `string`. To treat it as a `UserId` again, the receiver parses it with the branded schema, which is also where the value gets re-validated.
- How should tests create branded ids without weakening the guarantee?Parse fixtures through the same schemas, for example `OrderId.parse("...")`, so test data passes the same check as production data. If a cast is unavoidable, keep `as OrderId` inside one test helper rather than scattering it, because every cast is an unchecked claim the compiler will trust.
- Can parse tell a UserId string from an OrderId string?Not by the brand. Both schemas are `z.uuid()` underneath, so any valid UUID passes either one. If the two kinds must be distinguishable at runtime, the data itself has to differ, for example a prefix the schema checks with a regex. The brand only stops the compiler from mixing values once they are typed.
- .brand adds a hidden property to the parsed value at runtime.
- Branding makes parse reject an order id passed to the UserId schema.
- By default the input type is branded too, so callers must pass branded data.
- A branded UserId can no longer be passed where a plain string is expected.
- Calling .brand() with no type argument still creates a distinct brand.
Assumes Zod 4; the direction generic on .brand() ("out", "in", "inout") requires Zod 4.2 or later, and Zod 4 replaced Zod 3's ZodBranded class with a direct change to the inferred type.