Skip to content

Instantly share code, notes, and snippets.

@LukaJCB
Created April 28, 2025 04:20
Show Gist options
  • Save LukaJCB/56a2ff6138fa0cce297a62040917c270 to your computer and use it in GitHub Desktop.
Save LukaJCB/56a2ff6138fa0cce297a62040917c270 to your computer and use it in GitHub Desktop.
Dependent typescript solution
type FooOrBar = "foo" | "bar";
type MaybeFoo<T extends FooOrBar> = T extends "foo" ? {y: number} : {}
type Box<T extends FooOrBar> =
T extends "foo" ? { x: "foo"} & MaybeFoo<T> :
T extends "bar" ? { x: "bar"} & MaybeFoo<T> :
never;
function foo(f: Box<FooOrBar>): number {
if (f.x === "foo") {
return f.y
} else {
return 4
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment