I want (in function run) to get one of the known functions and pass corresponding arguments.
type Name = 'f1' | 'f2' | 'f3';
const fns = {
f1: () => {},
f2: (a: string) => {},
f3: (a: string, b: string) => {}
};
const argsArr = {
f1: [],
f2: ['str'],
f3: [1, 2]
};
function run(name: Name) {
const fn = fns[name];
const args = argsArr[name];
fn(...args); // "A spread argument must either have a tuple type or be passed to a rest parameter"
}
But at fn(...args) that causes the ts-error "A spread argument must either have a tuple type or be passed to a rest parameter". Because, as I think, TS doesnt think there is a guarantee that the args type is corresponding to the function. So, I'm looking for a way to narrow the type of name parameter, so to narrow/infer the type of fn (to make TS understand that although they may vary, they always correspond to each other).
Btw, I tried variants of the following, doesn't work:
function run<N extends Name, F extends Fn>(name: N) {
const fn= fns[name] as F;
type Args = Parameters<typeof fn>;
const args:Args = argsArr[name] as Args;
fn(...args);
}
Btw2, I didn't find typifying of comon decorators of functions (not TS Decorators) it would help.
You can add type for 'fns' object.
Then error is gone