Advertisement
Advanced TypeScript, Structural Typing & Duck Typing

How would you deliberately opt OUT of structural typing for a specific type using the 'branded type' (nominal typing emulation) technique?

Short answer

Add a unique, otherwise-unused 'brand' property (often typed with a unique symbol or a literal string tag) to a type — this forces TypeScript's structural check to require that exact brand property, which only values EXPLICITLY constructed as that branded type can satisfy…

Save TypeScript mock interview
Advertisement
AModel answer
Add a unique, otherwise-unused 'brand' property (often typed with a unique symbol or a literal string tag) to a type — this forces TypeScript's structural check to require that exact brand property, which only values EXPLICITLY constructed as that branded type can satisfy, effectively simulating nominal typing on top of a structural type system.
type UserId = string & { readonly __brand: 'UserId' };
type ProductId = string & { readonly __brand: 'ProductId' };

function createUserId(id: string): UserId { return id as UserId; }
function getUser(id: UserId) { /* ... */ }

const pid = 'p123' as ProductId;
// getUser(pid); // Error: ProductId is not assignable to UserId, despite both being strings
Real-world example
Preventing an entire class of bugs where two conceptually different IDs (both plain strings underneath) get accidentally swapped as function arguments.
Likely follow-ups
  • What's the runtime cost (if any) of using branded types, given the brand property doesn't actually exist on real string values?
Related topics