Created
October 15, 2022 21:10
-
-
Save DominikStyp/d818e88947cc4d2cb5f65f4a035c2296 to your computer and use it in GitHub Desktop.
TypeScript: Nominal Typing using symbols
This file contains 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
declare const Nominal: unique symbol; | |
type NominalType<TType, TNominal extends string> = TType & { | |
[Nominal]: TNominal; | |
}; | |
type UserId = NominalType<string, 'user_id'>; | |
type BookId = NominalType<string, 'book_id'>; | |
function doSomething(userId: UserId, bookId: BookId) { | |
console.log('OK'); | |
} | |
// this is OK | |
doSomething('123' as UserId, '456' as BookId); | |
// this is not OK | |
// doSomething('123', '456'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment