Created
July 9, 2025 20:22
-
-
Save rybla/db152fd7b8e2f4ab13cab8d2ef67646d to your computer and use it in GitHub Desktop.
newtype experiment 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
import { do_ } from "@/utility"; | |
type Newtype<R extends object, S extends keyof R, T> = R[S] extends void | |
? R & T | |
: never; | |
const X1: unique symbol = Symbol(); | |
type X1 = Newtype<{ [X1]: void }, typeof X1, number>; | |
const X2: unique symbol = Symbol(); | |
type X2 = Newtype<{ [X2]: void }, typeof X2, string>; | |
function square<A>(x: A, y: A) { | |
return [x, y]; | |
} | |
do_(() => { | |
const x1: X1 = 100 as X1; | |
const x2: X2 = "hello world" as X2; | |
square(x1, x1); | |
// @ts-expect-error newtype distinguishes | |
square(x1, x2); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment