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.

Solution

Use branded types (phantom types) to create nominally-typed primitives.

Code Snippets

Branded types for type-safe IDs

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

type UserId = Brand<string, 'UserId'>;
type PostId = Brand<string, 'PostId'>;

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

function getUser(id: UserId) { /* ... */ }

const uid = UserId('usr_123');
const pid = PostId('post_456');
getUser(uid);  // OK
// getUser(pid);  // Compile error!

Revisions (0)

No revisions yet.