Last active
April 28, 2025 01:28
-
-
Save LukaJCB/ac6f6158e5044581061036687bd1f9fd to your computer and use it in GitHub Desktop.
Dependent 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
type FooOrBar = "foo" | "bar" | |
type Box<T extends FooOrBar> = { | |
x: T | |
y: MaybeFoo<T> | |
} | |
type MaybeFoo<T extends FooOrBar> = T extends "foo" ? number : {} | |
// below does not compile | |
function either(f: Box<"foo" | "bar">): Box<"foo"> | Box<"bar"> { | |
if (f.x == "foo") return f //Type 'Box<"foo" | "bar">' is not assignable to type 'Box<"foo"> | Box<"bar">' | |
else return f | |
} | |
function foo(f: Box<FooOrBar>): number { | |
if (f.x == "foo") return f.y //Type 'number | {}' is not assignable to type 'number' | |
else return 4 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment