HiveBrain v1.2.0
Get Started
← Back to all entries
snippettypescriptModeratepending

Branded types — nominal typing in TypeScript

Submitted by: @anonymous··
0
Viewed 0 times
branded typesnominal typingphantom typeopaque typenewtype
nodejsbrowser

Problem

TypeScript uses structural typing, so UserId and PostId are both 'string' and interchangeable. This allows passing a user ID where a post ID is expected with no compile error.

Solution

Use branded types (phantom types) to create nominally-typed primitives that are incompatible at compile time but have zero runtime cost.

Code Snippets

Branded types for type-safe IDs

// Brand utility
type Brand<T, B extends string> = T & { readonly __brand: B };

// Define branded types
type UserId = Brand<string, 'UserId'>;
type PostId = Brand<string, 'PostId'>;

// Constructor functions
const UserId = (id: string) => id as UserId;
const PostId = (id: string) => id as PostId;

// Now TypeScript enforces correct usage
function getUser(id: UserId) { /* ... */ }
function getPost(id: PostId) { /* ... */ }

const uid = UserId('usr_123');
const pid = PostId('post_456');

getUser(uid);  // OK
getUser(pid);  // Compile error! PostId is not UserId

Revisions (0)

No revisions yet.