Skip to content

Instantly share code, notes, and snippets.

@DominikStyp
Created October 15, 2022 21:10
Show Gist options
  • Save DominikStyp/d818e88947cc4d2cb5f65f4a035c2296 to your computer and use it in GitHub Desktop.
Save DominikStyp/d818e88947cc4d2cb5f65f4a035c2296 to your computer and use it in GitHub Desktop.
TypeScript: Nominal Typing using symbols
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