【发布时间】:2020-01-02 17:30:00
【问题描述】:
我有一个接口,它接受一个可以是函数类型或字符串的函数(对于异步函数,因此 tsc 不会转译它们)。问题出在我的任务运行器上,我似乎无法弄清楚如何根据接口上的 func 属性来确定函数的参数行为。它推断它为string | (...args: any[]) => number),例如func: (x: number) => x + 1)。问题在于,当我尝试检查 run 函数调用中的 func 参数以使其在接受参数的函数上需要参数时,它没有正确检查它是否扩展了函数,而是将参数推断为 any[] 而不是比number。有人知道怎么做这样的事情吗?
我在这里的意思的例子:
interface ITask<T> {
id: number;
func: ((...args: any[]) => T) | string;
};
class Task<T> implements ITask<T> {
public id: number;
public func: ((...args: any[]) => T) | string;
constructor(opts: ITask<T>) {
this.id = opts.id;
this.func = opts.func;
}
}
class Runner {
constructor() { }
public run<T>(task: { func: T }, ...args: T extends (...args: infer Args) => any ? Args : any[]) {
if (typeof task.func === 'function')
return task.func(...args);
else
return eval(`(${task.func})`);
}
}
const task = new Task({ id: 1, func: (x: number) => x + 1 });
const runner = new Runner();
// should be expecting an argument, but func is not inferring from usage it's a function and not a string
runner.run(task);
【问题讨论】:
标签: typescript