TypeScript dùng structural typing (shape giống nhau là tương thích).
Branded types tạo nominal typing để ngăn nhầm lẫn giữa các string types semantically khác nhau (UserId vs Email).
typescript
type UserId = string & { readonly _brand: 'UserId' };
type Email = string & { readonly _brand: 'Email' };
// Factory function tạo branded value:
function makeUserId(id: string): UserId { return id as UserId; }
function sendMail(email: Email) { /* ... */ }
const id = makeUserId('abc123');
sendMail(id); // Error! UserId không phải EmailTypeScript uses structural typing (same shape = compatible).
Branded types create nominal typing to prevent confusing semantically different string types (UserId vs Email).
typescript
type UserId = string & { readonly _brand: 'UserId' };
type Email = string & { readonly _brand: 'Email' };
// Factory function to create branded value:
function makeUserId(id: string): UserId { return id as UserId; }
function sendMail(email: Email) { /* ... */ }
const id = makeUserId('abc123');
sendMail(id); // Error! UserId is not Email