Last active
January 18, 2021 12:16
-
-
Save StreetStrider/005b3e2c2ba7a95ccf4f2f64e76b692d to your computer and use it in GitHub Desktop.
opaque type
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 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://typescript-play.js.org/#code/FAFwngDgpgBAQgJwIYDsAmMA8AVAfDAXhmxgDIYBvGBKJNAexQBswZxoAuGAVxQEsAjt1gBnMAFsARvSYwAvsGAB6JW0iwAYvXqF4ydJhTcpUBLlDqYWnUSMmEZStVoNmrdlC69BwmGKky8hbQ8EgOtsaSpo5UNHSMLGqcPPxCohLSsgrAAGa8AMYgfIxW2jAAFChcdlEIAJRc1sAUwDBtziDcCCgVPUgipfR1wNl5KIXFPXBhvdWRpg2hCM2t7TSd3b0w-UvD2QBuMwAec-a6AIzAhw45jWVE1uXnw9cwklzT4UvlAEzDwEddABmXLA4CSMEA3SPIHDHLQ7TlWHghH0JH-QFET7o0FYsI4iF4hA44D5RgiGRQAB0THoAHNypiiDlhmSUBSmNTaQz4QQiJJWeTKTT6YzCPzhkA