Skip to content

Instantly share code, notes, and snippets.

@samrith-s
Last active December 15, 2022 17:39
Show Gist options
  • Save samrith-s/3763d0ad51754526966adfa4c76722b5 to your computer and use it in GitHub Desktop.
Save samrith-s/3763d0ad51754526966adfa4c76722b5 to your computer and use it in GitHub Desktop.
Branded tuple elements in TypeScript
/**
* 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]
@samrith-s
Copy link
Author

You can check out the playground for a live version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment