/** * Represents a branded type for nominal typing in TypeScript. * Useful for distinguishing types that have the same underlying structure * but represent different concepts (e.g., UserId vs ProductId). */ type Brand = T & { __brand: K }; // Example Usage: type UserId = Brand; type ProductId = Brand; type OrderId = Brand; function processUser(id: UserId) { console.log(`Processing user with ID: ${id}`); } function processProduct(id: ProductId) { console.log(`Processing product with ID: ${id}`); } const myUserId: UserId = 'user-123' as UserId; const myProductId: ProductId = 'prod-abc' as ProductId; processUser(myUserId); // OK // processUser(myProductId); // Type Error: Argument of type 'ProductId' is not assignable to parameter of type 'UserId'. console.log('--- Branded Types Demo ---'); console.log(`User ID: ${myUserId}`); console.log(`Product ID: ${myProductId}`); // If you try to assign directly without casting, TypeScript will treat them as strings: const anotherUserId: UserId = 'user-456' as UserId; // Needs casting to ensure type safety // const invalidUserId: UserId = 'prod-xyz' as ProductId; // Still a type error if you cast to the wrong brand