TypeScript Master (50 Qs)•Part 3: Enterprise Architecture, Compiler Internals & Performance (Senior / Staff)
How do you implement Nominal Typing (Branded Types) in TypeScript?
senior LevelCode ExampleFormsPerformanceTypeScript
In Simple Words:
Because TypeScript is structurally typed, a UserId (string) and an OrderId (string) are completely interchangeable, leading to catastrophic runtime bugs where an order ID is passed into a user deletion function!
Branded Types attach a unique compile-time phantom property:
typescript
declare const __brand: unique symbol;
type Brand<B> = { readonly [__brand]: B };
export type UserId = string & Brand<"UserId">;
export type OrderId = string & Brand<"OrderId">;
function createUserId(id: string): UserId { return id as UserId; }
function createOrderId(id: string): OrderId { return id as OrderId; }
function deleteUser(id: UserId) { /* ... */ }
const userId = createUserId("usr_123");
const orderId = createOrderId("ord_456");
deleteUser(userId); // Valid
// deleteUser(orderId); // Compile Error: Type 'OrderId' is not assignable to 'UserId'!