给出以下Typescript代码,我得到一个错误
TS2349: Cannot invoke an expression whose type lacks a call signature. Type 'AddReturnType' has no compatible call signatures.
AddReturnType
为什么不能使用该呼叫?
type AddReturnType = number | ((arg0: number) => number);
function add(x: number, y?: number) : AddReturnType {
if (!y) {
return (val) => val + y;
}
return x + y;
}
add(1)(2);
答案 0 :(得分:5)
TypeScript不能确定您要返回的是number
还是函数,并且只能调用两个选项之一。将两个函数签名分开:
function add(x: number): (number) => number;
function add(x: number, y: number): number;
function add(x, y?) {
if (!y) {
return (val) => val + y;
}
return x + y;
}
add(1)(2);
那是不是应该val + x
?