Q53: How do you achieve Nominal Typing in TypeScript using Branding (Flavoring)?
Because TypeScript uses structural typing, two primitive aliases (e.g., type UserId = string and type PostId = string) are interchangeable.
Branding attaches a unique phantom literal property tag to primitive types to make them nominally distinct.
Type Branding Pattern
type Brand<K, T> = K & { __brand: T };
type UserId = Brand<string, 'UserId'>;
type PostId = Brand<string, 'PostId'>;
const userId = "usr_100" as UserId;
const postId = "post_200" as PostId;
// const invalid: UserId = postId; // Error! 'PostId' brand is not assignable to 'UserId'💡 Attaching a unique brand property tag prevents accidental assignment between distinct types that share identical raw primitive structures.
Key Takeaways
- Branding prevents accidental interchange of identically structured primitive types.