Created
February 6, 2024 07:49
-
-
Save donchev7/69fe5265061bdbf79e5786e3229dfcce to your computer and use it in GitHub Desktop.
Branded types in typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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