9 Replies
andersgee
andersgee•2y ago
looked at this and your issue is essentially that the "...args" is a union of tuples, but must be a single tuple you must infer which one of the tuples it is somehow, probably with a switch statement or some typescript wizardry 😄
Christoph
Christoph•2y ago
The thing is, that the code, the auto-completion and type-hinting when using the function all works. It's really just a type error that I don't understand. Parameters<typeof myFunctions[TKey]> only returns the array of parameters needed for the required function. (e.g. type ParamsOfFirstFunction = Parameters<typeof myFunctions['firstFunction']> only returns one array/tuple).
andersgee
andersgee•2y ago
personally I would rewrite it so that your method takes 1 instead of 2, like this
// From third-party library:
const myFunctions = {
firstFunction(arg1: string, arg2: number) {
throw new Error("Not implemented");
},
secondFunction(arg1: bigint, arg2: number | null, arg3: boolean) {
throw new Error("Not implemented");
},
};

type Action =
| {
key: "firstFunction";
args: Parameters<typeof myFunctions["firstFunction"]>;
}
| {
key: "secondFunction";
args: Parameters<typeof myFunctions["secondFunction"]>;
};

export class Test {
public executeFunction(action: Action) {
switch (action.key) {
case "firstFunction":
myFunctions.firstFunction(...action.args);
break;
case "secondFunction":
myFunctions.secondFunction(...action.args);
break;
}
}
}
// From third-party library:
const myFunctions = {
firstFunction(arg1: string, arg2: number) {
throw new Error("Not implemented");
},
secondFunction(arg1: bigint, arg2: number | null, arg3: boolean) {
throw new Error("Not implemented");
},
};

type Action =
| {
key: "firstFunction";
args: Parameters<typeof myFunctions["firstFunction"]>;
}
| {
key: "secondFunction";
args: Parameters<typeof myFunctions["secondFunction"]>;
};

export class Test {
public executeFunction(action: Action) {
switch (action.key) {
case "firstFunction":
myFunctions.firstFunction(...action.args);
break;
case "secondFunction":
myFunctions.secondFunction(...action.args);
break;
}
}
}
Christoph
Christoph•2y ago
Hmm, let me see if that works when I make it generic.
Christoph
Christoph•2y ago
Unfortunately, the exact same error. And manually switching through all possible actions is not an option. The functions can change from time to time. Does anyone else have an idea?
awexis
awexis•2y ago
https://tsplay.dev/m0YeDW does this do what you want?
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
awexis
awexis•2y ago
@Christoph
Christoph
Christoph•2y ago
That's not quite right. When you call the function now, arg1 would be the array of arguments and arg2 would be undefined.
Want results from more Discord servers?
Add your server