Last active
February 1, 2022 19:06
-
-
Save nwellis/140b1674e74c2c4f1d22b65dba11f2ea to your computer and use it in GitHub Desktop.
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 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") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TS 🧙 @Beng89 thank you for this bit of gold 😲 💯 🥇