Nâng CaoTypeScript iconTypeScript

Branded types (nominal types) trong TypeScript là gì?

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 Email

Xem toàn bộ TypeScript cùng filter theo level & chủ đề con.

Mở danh sách TypeScript