Last active
December 15, 2022 17:39
-
-
Save samrith-s/3763d0ad51754526966adfa4c76722b5 to your computer and use it in GitHub Desktop.
Branded tuple elements 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
/** | |
* Simple Brand type to give us branding. It omits the `__brand` key so that | |
* it does not show up in auto-complete | |
*/ | |
type Brand<K, T> = T & Omit<{ | |
__brand: K | |
}, '__brand'> | |
const [latitude1, longitude1]: [Brand<"Latitude", number>, Brand<"Longitude", number>] = [0, 0] | |
/** | |
* We can also simplify this by creating specific "brands" for our tuple elements | |
*/ | |
type Latitude = Brand<"Latitude", number> | |
type Longitude = Brand<"Longitude", number> | |
const [latitude2, longitude2]: [Latitude, Longitude] = [0, 0] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can check out the playground for a live version.