Skip to content

Instantly share code, notes, and snippets.

@nwellis
Last active February 1, 2022 19:06
Show Gist options
  • Save nwellis/140b1674e74c2c4f1d22b65dba11f2ea to your computer and use it in GitHub Desktop.
Save nwellis/140b1674e74c2c4f1d22b65dba11f2ea to your computer and use it in GitHub Desktop.
type ParamBuilder<TArgs extends Record<string, any>, TReturn> = {
[K in keyof TArgs]: (arg: TArgs[K]) => ParamBuilder<Omit<TArgs, K>, TReturn>;
} & (keyof TArgs extends never ? { call(): TReturn } : {})
function builderFor<TArgs extends object, TReturn>(fn: (args: TArgs) => TReturn) {
const args: TArgs = {} as unknown as TArgs;
return new Proxy({}, {
get(self, prop) {
if (prop === "call") {
return () => fn(args);
}
return (value: any) => {
args[prop] = value
return this;
}
}
}) as unknown as ParamBuilder<TArgs, TReturn>;
}
function testFn(args: { color: "red" | "blue", size: "large" | "medium" }) {
return args.color;
}
const builder = builderFor(testFn)
.color("red")
.size("large")
@nwellis
Copy link
Author

nwellis commented Feb 1, 2022

TS 🧙 @Beng89 thank you for this bit of gold 😲 💯 🥇

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment