Skip to content

Instantly share code, notes, and snippets.

@Jason5Lee
Last active February 22, 2020 02:14
Show Gist options
  • Save Jason5Lee/333bd4255d8985b5355ede2ad403f8c0 to your computer and use it in GitHub Desktop.
Save Jason5Lee/333bd4255d8985b5355ede2ad403f8c0 to your computer and use it in GitHub Desktop.
TypeScript's opaque type.
type USD = number & { readonly __brand: unique symbol }
type EUR = number & { readonly __brand: unique symbol }
type Currency = USD | EUR;
function addCurrency<T extends Currency>(a: T, b: T): T {
return (a + b) as T;
}
addCurrency(5 as USD, 6 as USD);
addCurrency(5 as EUR, 7 as USD); // Compilation error.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment