Web Development
TypeScript
Subjective
Oct 04, 2025
Explain branded types and their use cases in TypeScript.
Detailed Explanation
Branded types add nominal typing to structural types using unique symbols or phantom properties.
Basic Branded Type:
type Brand = T & { __brand: B };
type UserId = Brand;
type ProductId = Brand;
function createUserId(id: string): UserId {
return id as UserId;
}
function createProductId(id: string): ProductId {
return id as ProductId;
}
// Usage
const userId = createUserId('user123');
const productId = createProductId('prod456');
// This prevents mixing different ID types
function getUser(id: UserId) { /* ... */ }
getUser(userId); // OK
// getUser(productId); // Error: ProductId not assignable to UserId
Phantom Type Implementation:
declare const __brand: unique symbol;
type Branded = T & { [__brand]: B };
type Email = Branded;
type Password = Branded;
function validateEmail(email: string): Email | null {
return email.includes('@') ? email as Email : null;
}
function hashPassword(password: string): Password {
return ('hashed_' + password) as Password;
}
// Type-safe authentication
function authenticate(email: Email, password: Password) {
// Implementation
}
const email = validateEmail('user@example.com');
const password = hashPassword('secret123');
if (email) {
authenticate(email, password); // Type-safe
}
Benefits:
• Prevent mixing of similar but distinct types
• Add semantic meaning to primitive types
• Catch errors at compile time
• Improve code documentation and clarity.
Discussion (0)
No comments yet. Be the first to share your thoughts!
Share Your Thoughts