Skip to content

Instantly share code, notes, and snippets.

@StreetStrider
Last active January 18, 2021 12:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StreetStrider/005b3e2c2ba7a95ccf4f2f64e76b692d to your computer and use it in GitHub Desktop.
Save StreetStrider/005b3e2c2ba7a95ccf4f2f64e76b692d to your computer and use it in GitHub Desktop.
opaque type
type Brand <T> = T & { readonly type: unique symbol }
// type Foo = Brand<number>
type Foo = number & { readonly type: unique symbol }
type Bar = number & { readonly type: unique symbol }
function Foo (n: number): Foo
{
return (n as Foo)
}
function Bar (n: number): Bar
{
return (n as Bar)
}
var x: number = 1
var f: Foo = Foo(1)
var b: Bar = Bar(2)
x = 3
f = 3
b = 3
x = Foo(3)
f = Foo(3)
b = Foo(3)
x = Bar(3)
f = Bar(3)
b = Bar(3)
console.log(x == f)
console.log(f == b)
console.log(x == b)