Typescript从动态函数中获取参数



我想获得保存在不同模块中的函数的参数。例如,myFunction获得我想要的函数,然后应该使用正确的参数执行它。然而,参数行显示了以下错误:类型'函数'不满足约束

public Execute(module: any, myFunction: Function, params: string){
type TestArgsType = Parameters<typeof myFunction>;
myFunction.apply(module, params);
}

是否有任何方法使用参数与函数传递作为参数?

可以,如果你把你的通用。

const Execute = <T extends (...args: unknown[]) => unknown>(module: any, myFunction: T, params: string){
type TestArgsType = Parameters<T>;

const Execute = <TestArgsType extends unknown[]>(module: any, myFunction: (...args: T) => unknown, params: string){

你也可以考虑输入module更精确,或者至少是unknown——使用any违背了TypeScript的目的。

最新更新