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.

Diagram: without a brand, MemberId and BookId both resolve to string; with a brand they carry different brands and cannot be swapped

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"Source:https://dev.to/sascha-ms/typescript-branded-types-type-safe-ids-in-lambda-38hl

Related posts