I have a function A that takes another function as an argument. Inside function A I want to execute given function with one explicit parameter and rest with given parameter of a function. Like this.
function t(g: number, p: any, b: any): void {
console.log(g)
console.log(p)
console.log(b)
}
function execute(fn: (t: number, ...args: any[]) => void) {
// But this is not working...getting this error --- 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
const ar = fn.arguments.slice(1)
fn(3, ...ar)
}
execute(t)
How can I capture args execute with fn in strict mode?
In addition to the fact that you're using strict mode, it doesn't make sense to use fn.arguments here since fn isn't being passed any arguments. Instead you can add an args parameter to execute and pass them to fn.
function t(g: number, p: any, b: any): void {
console.log(g);
console.log(p);
console.log(b);
}
function execute<TRestArgs extends any[]>(fn: (g: number, ...args: TRestArgs) => void, ...args: TRestArgs) {
fn(3, ...args);
}
execute(t, "p", "b");
I've added the TRestArgs type parameter to provide type safety. Now execute(t, "p", "b", "x") will raise an error because t only has three parameters.