0
0
Typescriptprogramming~5 mins

Branded types for safety in Typescript

Choose your learning style9 modes available
Introduction

Branded types help keep different kinds of data separate even if they look the same. This stops mistakes where you mix things up by accident.

When you have two values that are both strings but mean different things, like UserID and ProductID.
When you want to avoid mixing up similar numbers, like OrderNumber and InvoiceNumber.
When you want the computer to catch errors early by making types more specific.
When you want to add extra meaning to simple types without changing their runtime behavior.
Syntax
Typescript
type Brand<K, T> = K & { __brand: T };

// Example:
type UserID = Brand<string, 'UserID'>;
type ProductID = Brand<string, 'ProductID'>;

The Brand type combines a base type K with a unique tag T to create a new type.

This tag __brand does not exist at runtime; it only helps TypeScript check types.

Examples
This shows two branded types that both use strings but are treated differently by TypeScript.
Typescript
type UserID = Brand<string, 'UserID'>;
type ProductID = Brand<string, 'ProductID'>;

const userId: UserID = 'abc123' as UserID;
const productId: ProductID = 'abc123' as ProductID;

// Error if you try to assign one to the other:
// const wrong: UserID = productId;
Function expects a branded UserID, so you must cast or create the right type to call it.
Typescript
function getUser(id: UserID) {
  console.log(`User ID is ${id}`);
}

const id = 'user-1' as UserID;
getUser(id);
Sample Program

This program defines two branded types and a function that only accepts UserID. It shows how TypeScript prevents mixing them up.

Typescript
type Brand<K, T> = K & { __brand: T };

type UserID = Brand<string, 'UserID'>;
type ProductID = Brand<string, 'ProductID'>;

function printUserId(id: UserID) {
  console.log(`User ID: ${id}`);
}

const userId = 'user123' as UserID;
const productId = 'prod123' as ProductID;

printUserId(userId);

// The next line would cause a TypeScript error if uncommented:
// printUserId(productId);
OutputSuccess
Important Notes

Branded types only exist during development and do not add code at runtime.

You must use as to tell TypeScript when you want to treat a value as a branded type.

This technique helps catch bugs early by making types more specific.

Summary

Branded types add a hidden tag to simple types to keep them distinct.

They help avoid mixing up similar data like IDs or codes.

They improve safety without changing runtime behavior.