Skip to content

Instantly share code, notes, and snippets.

@LukaJCB
Last active April 28, 2025 01:28
Show Gist options
  • Save LukaJCB/ac6f6158e5044581061036687bd1f9fd to your computer and use it in GitHub Desktop.
Save LukaJCB/ac6f6158e5044581061036687bd1f9fd to your computer and use it in GitHub Desktop.
Dependent typescript
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