我有以下代码:
task = (
data: string,
taskCallback: (data: any) => any
) => {
};
如何使这更加通用,以便successCallback可以是一个接收和返回任何内容的函数,或者它可能是一个甚至不提供的参数?
答案 0 :(得分:0)
如果我确实理解了您的请求,那么定义应该是 Function
:
var task = (
data: string,
//taskCallback: (data: any) => any,
taskCallback: Function // here we go, requiring the function
) => { ...};
然后我们可以拥有这些:
var callback1 = () => { }
var callback2 = (data: any) => { }
var callback3 = () => { return 1; }
这将编译:
task("data", callback1);
task("data", callback2);
task("data", callback3);
task("data", null);
但这不是:
task("data", 1); // 1 is number not a function
答案 1 :(得分:0)
您拥有的已经可以满足您的需求
var task = (
data: string,
taskCallback: (data: any) => any
) => {
};
来自 Radim 的答案的例子:
var callback1 = () => { }
var callback2 = (data: any) => { }
var callback3 = () => { return 1; }
task("data", callback1);
task("data", callback2);
task("data", callback3);
task("data", null);
task("data", 1); // 1 is number not a function
原因:回调函数可以使 less 比预期的参数数量少。更多:https://github.com/Microsoft/TypeScript/wiki/Type%20Compatibility#comparing-two-functions