Skip to content

Instantly share code, notes, and snippets.

@djcsdy
Last active January 18, 2017 10:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djcsdy/fb1f85a4e49f25f3bedb18960d8c5859 to your computer and use it in GitHub Desktop.
Save djcsdy/fb1f85a4e49f25f3bedb18960d8c5859 to your computer and use it in GitHub Desktop.
type Branded<T, U extends string> = T & { [Symbol.species]: U };
// if targeting ES5, change to:
// type Branded<T, U> = T & { ['Brand']: U };
// FOO
type FooId = Branded<number, 'FooId'>;
// BAR
type BarId = Branded<number, 'BarId'>;
// Usage Demo
let fooId: FooId;
let barId: BarId;
// Safety!
fooId = barId; // error
barId = fooId; // error
// Newing up
fooId = 1 as FooId;
barId = 2 as BarId;
// Both types are compatible with the base
let n: number;
n = fooId;
n = barId;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment