TypeScript branded types give a plain string an invisible brand, so the compiler no longer mixes up a member ID with a book ID. Sounds like a detail. Yet exactly this kind of detail slips through every code review: two parameters of type string, passed in the wrong order once, and a record ends up under the wrong key in DynamoDB. No test fails, because the data looks perfectly valid.
I care about this topic because serverless backends are full of such IDs. Every Lambda function receives identifiers from an event, builds keys from them, calls other services and returns identifiers again. In this article I show you how a few lines of type code get rid of a whole class of bugs without executing a single extra byte at runtime. At the end you will have a small, runnable loan API for a library, built with the Serverless Framework.
In short
Branded types attach a brand to a simple type such as string or number that only the compiler can see. This lets TypeScript tell apart two IDs or amounts that look identical at runtime. The biggest pitfall is an “as” on every corner: the brand belongs in exactly one place, behind a check at the system boundary.
What you will learn in this article
- Why TypeScript does not detect swapped string IDs out of the box
- How to build a brand type with unique symbol in five lines
- How smart constructors and Zod assign the brand at the Lambda boundary
- How to use @ts-expect-error to prove that wrong code does not compile
Why TypeScript branded types? The problem with swapped IDs
Picture a small library app. Members borrow books, and every loan has a due date and a late fee per day. A typical function for this looks like this:
async function lendBook(memberId: string, bookId: string, days: number) {
// ...
}
// Somewhere else in the code, three weeks later:
await lendBook(request.bookId, request.memberId, 14);
The call compiles without complaint. Both parameters are strings, so TypeScript is happy. At runtime this produces a DynamoDB item with the partition key MEMBER#B-123456. Nobody notices until someone wonders why a member is called “B-123456”. With money it gets even worse: you cannot tell from the number 50 whether it means 50 cents or 50 euros.
This is exactly where TypeScript branded types come in. They turn the general string into a specific MemberId type that behaves exactly like a string at runtime but is no longer interchangeable with a BookId for the compiler.
Structural typing in a nutshell
To see why the trick is needed, let’s take a quick look under the hood. TypeScript checks types structurally: two types are compatible if they have the same properties. The name of the type does not matter. Java and C# work differently, where the declared name counts (nominal typing).
For objects this is usually handy. For simple aliases, however, it means that type MemberId = string is just a second name for string. The alias documents your intent but protects you from nothing. By the way, the TypeScript team has known about the wish for nominal types for years: the issue “Support some non-structural (nominal) type matching” has been open since 2014.
Without a brand, MemberId and BookId are just names for string; with a brand, the compiler can tell them apart.
The solution is therefore a small trick. You add a property to the type that does not exist at runtime. Structurally, MemberId and BookId now differ by exactly this property, and the compiler can tell them apart.
How TypeScript branded types work
The brand type with unique symbol
The most common variant is an intersection type made of the base type and an object carrying a brand. A unique symbol serves as the key. TypeScript treats this symbol type as unique: two such symbols are never compatible with each other, and they are only allowed on const declarations or readonly static properties.
// src/brand.ts
// A symbol that exists only at compile time. There is no value behind it,
// so nobody can accidentally create the brand at runtime.
declare const brand: unique symbol;
// Brand<string, "BookId"> is a string with an invisible brand.
export type Brand<T, B extends string> = T & { readonly [brand]: B };
The declare matters. It tells the compiler “this symbol exists” without anything showing up in the generated JavaScript. After compilation a MemberId is a perfectly normal string again. And because the symbol is not exported, no other module can rebuild the brand by hand.
You will also find the simpler variant string & { __brand: "MemberId" } online. It works in a similar way but has two drawbacks: the __brand property appears in autocompletion, and any library that happens to use the same convention creates compatible brands. With the symbol you are on the safe side.
Smart constructors instead of “as” everywhere
You only get a brand through a type assertion with as. If you did that all over the code, nothing would be gained. That is why the as belongs in a single function that first checks whether the value really fits. Such functions are called smart constructors: they are the only official way from a raw string to a branded ID.
The benefit is twofold. First, a MemberId can only come into existence in the rest of the code after it has been checked. Second, the format rule lives in exactly one place instead of being scattered across handlers, tests and helpers.
Step by step: TypeScript branded types in a Lambda function
Now it gets practical. We build an HTTP API with a POST /loans endpoint that stores a loan in DynamoDB. Members have IDs like M-000042, books B-123456, and late fees are calculated in cents.
Prerequisites
- Node.js 24 and npm
- An AWS account with configured credentials if you want to deploy (not needed for type checks and tests)
- The Serverless Framework v4 (
npm i -g serverless) - Basic knowledge of TypeScript and AWS Lambda
Step 1: Create the project
mkdir library-loans && cd library-loans
npm init -y
npm install zod @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb
npm install -D typescript vitest @types/aws-lambda @types/node
The tsconfig.json is deliberately short. What matters is strict; without strict mode, branded types lose much of their effect. Also add "type": "module" to your package.json, plus the scripts "typecheck": "tsc --noEmit" and "test": "vitest run".
{
"compilerOptions": {
"target": "ES2023",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"types": ["node"]
},
"include": ["src", "test"]
}
Step 2: Define brands and IDs
Create the file src/brand.ts from above without changes. The three ID types build on it, each with a smart constructor. For new loans we generate the ID ourselves. The random generator can be passed in from outside so that the function stays testable.
// src/ids.ts
import type { Brand } from "./brand.js";
export type MemberId = Brand<string, "MemberId">;
export type BookId = Brand<string, "BookId">;
export type LoanId = Brand<string, "LoanId">;
const MEMBER_ID = /^M-\d{6}$/;
const BOOK_ID = /^B-\d{6}$/;
const LOAN_ID = /^L-[0-9a-f]{8}$/;
// Smart constructors: the only way to a branded ID leads through a check.
export function memberId(raw: string): MemberId {
if (!MEMBER_ID.test(raw)) {
throw new Error(`Invalid member ID: ${raw}`);
}
return raw as MemberId;
}
export function bookId(raw: string): BookId {
if (!BOOK_ID.test(raw)) {
throw new Error(`Invalid book ID: ${raw}`);
}
return raw as BookId;
}
export function newLoanId(random: () => string = () => crypto.randomUUID()): LoanId {
const id = `L-${random().replaceAll("-", "").slice(0, 8)}`;
if (!LOAN_ID.test(id)) {
throw new Error(`Invalid loan ID: ${id}`);
}
return id as LoanId;
}
Step 3: Brand money amounts in cents
Numbers work the same way. If you store amounts as decimal euros, you invite rounding errors. A Cents brand forces you to keep amounts as whole numbers, and the constructor rejects everything else.
// src/money.ts
import type { Brand } from "./brand.js";
// Amounts are always whole cents, never decimal euros.
export type Cents = Brand<number, "Cents">;
export function cents(value: number): Cents {
if (!Number.isSafeInteger(value) || value < 0) {
throw new Error(`Invalid cent amount: ${value}`);
}
return value as Cents;
}
export function addCents(a: Cents, b: Cents): Cents {
return cents(a + b);
}
export function formatEuro(value: Cents): string {
return new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(value / 100);
}
Watch out for addCents: if you add two Cents values with +, TypeScript sees the result as a plain number again. The brand does not survive arithmetic. That is why the result goes through cents() once more.
Step 4: Build DynamoDB keys type-safely
In single-table design, keys are often composed of a prefix and an ID. A brand helps here too: a function that expects a PartitionKey will not accept some randomly concatenated string.
// src/keys.ts
import type { Brand } from "./brand.js";
import type { BookId, MemberId } from "./ids.js";
// Composite DynamoDB keys get their own brand as well.
export type PartitionKey = Brand<string, "PartitionKey">;
export type SortKey = Brand<string, "SortKey">;
export const memberPk = (id: MemberId) => `MEMBER#${id}` as PartitionKey;
export const loanSk = (id: BookId) => `LOAN#${id}` as SortKey;
Step 5: Parse at the system boundary with Zod
Now comes the crucial part. Everything that comes in from outside is unknown at first. At this boundary you check the data thoroughly once, and from then on the rest of the code only works with branded types. Zod is a good fit: first regex() checks the format, then transform() turns the string into the branded ID via the smart constructor.
// src/schemas.ts
import { z } from "zod";
import { bookId, memberId } from "./ids.js";
// Zod checks the format, the smart constructors return the branded types.
export const LoanRequest = z.object({
memberId: z.string().regex(/^M-\d{6}$/).transform(memberId),
bookId: z.string().regex(/^B-\d{6}$/).transform(bookId),
days: z.number().int().min(1).max(28).default(14),
});
export type LoanRequest = z.output<typeof LoanRequest>;
🎬 Flow: where the brand is assigned – this animated diagram only runs on my site: watch it on sascha-ms.de
Step 6: Service, repository and handler
The service only knows branded types. It knows nothing about HTTP or JSON, which makes it easy to test. The repository is an interface, so the test gets by without AWS.
// src/loan-service.ts
import { newLoanId, type BookId, type LoanId, type MemberId } from "./ids.js";
import { cents, type Cents } from "./money.js";
export interface Loan {
loanId: LoanId;
memberId: MemberId;
bookId: BookId;
dueDate: string;
lateFeePerDay: Cents;
}
export interface LoanRepository {
save(loan: Loan): Promise<void>;
}
const LATE_FEE_PER_DAY = cents(50);
// The parameter order is now type-checked:
// lendBook(bookId, memberId) no longer compiles.
export async function lendBook(
repo: LoanRepository,
member: MemberId,
book: BookId,
days: number,
now: Date = new Date(),
): Promise<Loan> {
const due = new Date(now.getTime() + days * 24 * 60 * 60 * 1000);
const loan: Loan = {
loanId: newLoanId(),
memberId: member,
bookId: book,
dueDate: due.toISOString().slice(0, 10),
lateFeePerDay: LATE_FEE_PER_DAY,
};
await repo.save(loan);
return loan;
}
The DynamoDB repository uses the key functions from step 4. The condition attribute_not_exists(sk) prevents the same book from being stored twice for the same member.
// src/dynamo-repository.ts
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, PutCommand } from "@aws-sdk/lib-dynamodb";
import { loanSk, memberPk } from "./keys.js";
import type { Loan, LoanRepository } from "./loan-service.js";
export class DynamoLoanRepository implements LoanRepository {
constructor(
private readonly tableName: string,
private readonly doc = DynamoDBDocumentClient.from(new DynamoDBClient({})),
) {}
async save(loan: Loan): Promise<void> {
await this.doc.send(
new PutCommand({
TableName: this.tableName,
Item: { pk: memberPk(loan.memberId), sk: loanSk(loan.bookId), ...loan },
// A member can only borrow the same book once at a time.
ConditionExpression: "attribute_not_exists(sk)",
}),
);
}
}
The handler stays lean: read JSON, validate with Zod, call the service. It answers invalid input with status 400 without revealing internal details.
// src/handler.ts
import type { APIGatewayProxyEventV2, APIGatewayProxyResultV2 } from "aws-lambda";
import { DynamoLoanRepository } from "./dynamo-repository.js";
import { lendBook, type LoanRepository } from "./loan-service.js";
import { LoanRequest } from "./schemas.js";
const json = (statusCode: number, body: unknown): APIGatewayProxyResultV2 => ({
statusCode,
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
export function createHandler(repo: LoanRepository) {
return async (event: APIGatewayProxyEventV2): Promise<APIGatewayProxyResultV2> => {
let raw: unknown;
try {
raw = JSON.parse(event.body ?? "{}");
} catch {
return json(400, { message: "Body is not valid JSON" });
}
// At the system boundary, a string becomes a MemberId or BookId.
const parsed = LoanRequest.safeParse(raw);
if (!parsed.success) {
return json(400, { message: "Invalid request", issues: parsed.error.issues.map((i) => i.path.join(".")) });
}
const { memberId, bookId, days } = parsed.data;
const loan = await lendBook(repo, memberId, bookId, days);
return json(201, loan);
};
}
export const handler = createHandler(new DynamoLoanRepository(process.env.TABLE_NAME ?? "library-loans"));
Step 7: Test, including the types
With branded types you want to check two things. First, the runtime behavior of the smart constructors and the handler, which Vitest takes care of. Second, the types themselves: wrong code should not compile at all. // @ts-expect-error is ideal for this. If the following line does not produce a type error, tsc reports an error because the directive is unused. This turns every such line into a small test.
// test/types.check.ts
// This file is not executed, only checked by "tsc --noEmit".
// Every line with @ts-expect-error MUST produce a type error.
import { z } from "zod";
import { bookId, memberId, type BookId, type MemberId } from "../src/ids.js";
import { lendBook, type LoanRepository } from "../src/loan-service.js";
import { cents, type Cents } from "../src/money.js";
declare const repo: LoanRepository;
const member = memberId("M-000042");
const book = bookId("B-123456");
void lendBook(repo, member, book, 14);
// @ts-expect-error – swapped parameters
void lendBook(repo, book, member, 14);
// @ts-expect-error – a plain string is not a BookId
const plain: BookId = "B-123456";
// A branded ID is still a string and can be read anywhere.
const asText: string = member;
// @ts-expect-error – decimal euros instead of cents
const fee: Cents = 0.5;
const total: number = cents(150) + cents(50); // result is just a number again
// @ts-expect-error – Zod brands and your own brands are different types
const fromZod: MemberId = z.string().brand<"MemberId">().parse("M-000042");
void plain, asText, fee, total, fromZod;
// test/ids.test.ts
import { describe, expect, it } from "vitest";
import { bookId, memberId, newLoanId } from "../src/ids.js";
import { addCents, cents, formatEuro } from "../src/money.js";
describe("Smart Constructors", () => {
it("accepts valid IDs", () => {
expect(memberId("M-000042")).toBe("M-000042");
expect(bookId("B-123456")).toBe("B-123456");
});
it("rejects swapped or broken IDs", () => {
expect(() => memberId("B-123456")).toThrow("Invalid member ID");
expect(() => bookId("123456")).toThrow("Invalid book ID");
});
it("creates loan IDs in the expected format", () => {
expect(newLoanId(() => "1a2b3c4d-0000-0000-0000-000000000000")).toBe("L-1a2b3c4d");
});
});
describe("Cents", () => {
it("only calculates with whole cent amounts", () => {
expect(addCents(cents(150), cents(50))).toBe(200);
expect(() => cents(1.5)).toThrow("Invalid cent amount");
expect(formatEuro(cents(250))).toMatch(/^2,50\s€$/);
});
});
// test/handler.test.ts
import type { APIGatewayProxyEventV2, APIGatewayProxyStructuredResultV2 } from "aws-lambda";
import { describe, expect, it } from "vitest";
import { createHandler } from "../src/handler.js";
import type { Loan, LoanRepository } from "../src/loan-service.js";
class InMemoryRepo implements LoanRepository {
loans: Loan[] = [];
async save(loan: Loan) {
this.loans.push(loan);
}
}
const event = (body: unknown) => ({ body: JSON.stringify(body) }) as APIGatewayProxyEventV2;
describe("POST /loans", () => {
it("creates a loan", async () => {
const repo = new InMemoryRepo();
const res = (await createHandler(repo)(
event({ memberId: "M-000042", bookId: "B-123456", days: 7 }),
)) as APIGatewayProxyStructuredResultV2;
expect(res.statusCode).toBe(201);
expect(repo.loans[0]).toMatchObject({ memberId: "M-000042", bookId: "B-123456", lateFeePerDay: 50 });
});
it("rejects swapped IDs with 400", async () => {
const repo = new InMemoryRepo();
const res = (await createHandler(repo)(
event({ memberId: "B-123456", bookId: "M-000042" }),
)) as APIGatewayProxyStructuredResultV2;
expect(res.statusCode).toBe(400);
expect(repo.loans).toHaveLength(0);
});
});
Both checks run locally without AWS access:
npm run typecheck
npm test
Expected result: tsc finishes without output, and Vitest reports Test Files 2 passed and Tests 6 passed. If you delete one of the @ts-expect-error lines as an experiment, you will see the error message that protects you from swapped values in real code.
Step 8: Deploy with the Serverless Framework
The serverless.yml creates the function, an HTTP API and the table. The Serverless Framework v4 builds TypeScript handlers itself with esbuild, so you do not need an extra plugin. Its IAM role may only run PutItem on exactly this table.
# serverless.yml
service: library-loans
provider:
name: aws
runtime: nodejs24.x
region: eu-central-1
architecture: arm64
memorySize: 256
timeout: 10
environment:
TABLE_NAME: ${self:service}-${sls:stage}
iam:
role:
statements:
- Effect: Allow
Action: dynamodb:PutItem
Resource: !GetAtt LoansTable.Arn
functions:
lendBook:
handler: src/handler.handler
events:
- httpApi:
path: /loans
method: post
resources:
Resources:
LoansTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: ${self:service}-${sls:stage}
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: pk
AttributeType: S
- AttributeName: sk
AttributeType: S
KeySchema:
- AttributeName: pk
KeyType: HASH
- AttributeName: sk
KeyType: RANGE
serverless deploy --stage dev
curl -s -X POST "https://<your-api-id>.execute-api.eu-central-1.amazonaws.com/loans" \
-H "content-type: application/json" \
-d '{"memberId":"M-000042","bookId":"B-123456","days":7}'
The response is a JSON object with loanId, dueDate and lateFeePerDay: 50. If you send the IDs swapped, you get status 400. To clean up, run serverless remove --stage dev.
A word on cost and security: the brands themselves cost nothing at runtime, because they disappear completely during compilation. The table uses on-demand billing, so a few test calls cost a fraction of a cent. Keep in mind that branded types do not replace input validation. They only document that validation happened. The actual security comes from the validation in step 5 and the narrowly scoped IAM role.
Common mistakes with branded types
The most common mistake is as everywhere. If you write value as MemberId in every other place, you have brands but no guarantee anymore. A simple rule helps: as to a branded type only appears in smart constructors and test data. A lint check or a quick grep during review finds the outliers.
Second, the brand is lost at every boundary where data is serialized. Whatever comes from JSON.parse, DynamoDB, SQS or an environment variable is a plain string again. That is not a bug but intended: this is exactly where the next check belongs. When you read data from DynamoDB, a schema pays off there as well.
Third, brands do not survive arithmetic or string methods. memberId.trim() returns a plain string, cents(a) + cents(b) a plain number. Plan for these spots deliberately, as with addCents.
Fourth, you should not brand everything. A brand pays off where values are easily confused: IDs of different entities, units such as cents and euros or milliseconds and seconds, validated versus unvalidated values. For a display name or a description it adds little.
Fifth, and this one is easy to miss: brands from different sources do not match. An ID created with Zod’s .brand<"MemberId">() is not a MemberId from your own Brand type, even though both have the same name. The type check in step 7 shows this with the last @ts-expect-error line.
Zod .brand() or your own brand type?
Zod ships its own solution with .brand(). The type returned by z.infer is then the base type plus a Zod brand. According to the Zod documentation, only the output type is branded by default, and since Zod 4.2 a second type parameter lets you brand the input as well. For projects where every piece of data goes through a Zod schema anyway, this is convenient.
Still, I prefer my own Brand type with smart constructors. The reason: the domain logic does not depend on the validation library. Service and repository only import ids.ts, and if you later swap Zod for Valibot or the Powertools Parser, only the schema file changes. Pick one variant per project, though, or you will trip over the fifth mistake from the previous section.
My take
For me, TypeScript branded types are among the tools with the best ratio of effort to benefit. Five lines of type code, a few smart constructors, and a whole category of bugs shows up while you type instead of in production. Especially in serverless applications, where many small functions pass IDs to each other, this pays off quickly.
I also see the limits. Branded types are a convention, not a language feature. Anyone on the team who does not understand why they exist will cast them away at the first error message. That is why I would not introduce them as a big refactoring. I would start where it has already hurt once: with the two IDs that most often appear next to each other as parameters. And I would briefly explain to the team why validation happens at the system boundary and nowhere else.
Where I disagree: some articles recommend branding every single primitive value. That makes code hard to read and tests cumbersome. A handful of well-chosen brands achieves more than fifty that nobody can keep track of.
FAQ
Do TypeScript branded types have a runtime cost?
No. The brand exists only for the compiler and disappears completely during compilation. The only runtime cost comes from the checks in your smart constructors, and you need those anyway.
What is the difference between branded types and opaque types?
The terms are often used interchangeably. Strictly speaking, a branded type stays compatible with its base type, so you can read a MemberId anywhere a string is expected. An opaque type hides the base type completely. In TypeScript, the branded variant is the usual one.
Do branded types work with JSON and DynamoDB?
Yes, because only the plain value is stored at runtime. When you read it back, though, you get a plain string or number again. That is why you validate data from JSON, DynamoDB or SQS again and reassign the brand there through the smart constructor.
Do I need a library for branded types?
No. The brand type from this article has no dependencies. Libraries like Zod offer their own brands, which is handy if everything goes through their schemas anyway.
Your next step
Find a function in your code with two or more string parameters that expect IDs of different things. Create a brand type and a smart constructor for each of these IDs and run tsc. The error messages immediately show you where the values come from and where the system boundary really is. If you want to go deeper into validation, see how to validate Lambda events with Powertools Parser and Zod. For testing, Lambda unit tests with Vitest is a good companion, and you will find an example of validated uploads in the article on the S3 presigned URL.
Which two values get mixed up most often in your code? Let me know in the comments.
All code from this article, ready to run: smirowstanitzok/sascha-ms-examples
Sources
- TypeScript Handbook: Type Compatibility
- TypeScript Handbook: Symbols (unique symbol)
- TypeScript issue #202: Support some non-structural (nominal) type matching
- Zod documentation: Defining schemas, section Branded types
- AWS Lambda: Lambda runtimes
Tested on 11/14/2026 with TypeScript 7.0.2, Zod 4.6.7, Vitest 5.1.0 and Node.js 22: tsc --noEmit without errors, all six tests green. The serverless.yml was validated as YAML, not deployed.
This post was created with AI assistance.
👉 Next step: New here? My start page collects the best articles, tools and learning paths in one place.
📬 Stay updated: New articles on serverless, AI and leading tech teams via RSS, browser push or the weekly newsletter (in German).
Originally published on sascha-ms.de. More articles on serverless, AI in everyday development and leading tech teams: sascha-ms.de/en

Top comments (0)