snippettypescriptModeratepending
Branded types -- nominal typing in TypeScript
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.