Last active
January 18, 2017 10:51
-
-
Save djcsdy/fb1f85a4e49f25f3bedb18960d8c5859 to your computer and use it in GitHub Desktop.
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
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