打字稿返回值或咖喱函数

时间:2019-01-29 17:44:36

标签: javascript typescript currying

给出以下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);

1 个答案:

答案 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