Skip to content

Instantly share code, notes, and snippets.

@donchev7
Created February 6, 2024 07:49
Show Gist options
  • Save donchev7/69fe5265061bdbf79e5786e3229dfcce to your computer and use it in GitHub Desktop.
Save donchev7/69fe5265061bdbf79e5786e3229dfcce to your computer and use it in GitHub Desktop.
Branded types in typescript
export type Branded<T, K extends string = 'BRANDED_TYPE'> = T & { __opaque__?: K };
type Brand = {
User: Branded<string, 'User'>,
Product: Branded<string, 'Product'>,
}
function getUser(userId: Brand['User']) {
// get user
}
const userId: Brand['User'] = '12'
const productId: Brand['Product'] = '34';
getUser('hello') // works
getUser(userId) // works
getUser(productId) // Type '"Product"' is not assignable to type '"User"'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment