What does the following type implement and what is it useful for? type Opaque = T & { readonly __brand: Brand }; type UserId = Opaque; type ProductId = Opaque;

TypeScript Professional Hard

TypeScript Professional — Hard

What does the following type implement and what is it useful for? type Opaque = T & { readonly __brand: Brand }; type UserId = Opaque; type ProductId = Opaque;

Key points

  • Opaque type with __brand enforces nominal typing
  • UserId and ProductId are distinct despite being strings
  • Prevents accidental interchangeability at runtime
  • __brand property adds unique identity to the types

Ready to go further?

Related questions