javascript / expert
Snippet
Nominal Typing via Branded Types
TypeScript uses structural typing, meaning any string can be passed where another string is expected. Branded types simulate nominal typing, preventing logical errors such as accidentally swapping a User ID with an Order ID, which is critical for security and data integrity in large-scale applications.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
type Brand<K, T> = K & { __brand: T };type UserId = Brand<string, 'User'>;type OrderId = Brand<string, 'Order'>;function processOrder(userId: UserId, orderId: OrderId) {// Business logic}const myUser = 'abc' as UserId;const myOrder = 'xyz' as OrderId;processOrder(myUser, myOrder); // Success// processOrder(myOrder, myUser); // TypeScript Error!
nextjs
Breakdown
1
type Brand<K, T> = K & { __brand: T };
Creates an intersection type that adds a unique property to a primitive type to distinguish it.
2
type UserId = Brand<string, 'User'>;
Defines a unique type for User IDs that is technically a string but incompatible with other 'branded' strings.
3
processOrder(myOrder, myUser);
The compiler blocks this call because the brand tags do not match, even though both are strings.