JavaScript/Typescript 没有 class 的可链接函数

JavaScript/Typescript chainable function without class

我正在尝试在 Typescript 中正确编码我的可链接函数。下面是代码

  const sum = (val: number | undefined) => {
    let internal = Number(val);
    if (val) {
      return function sumup(_val: number | undefined) {
        if (_val && internal !== undefined) {
          internal += _val;
          return sumup;
        }
        return internal;
      };
    }
    return internal;
  };

  console.log('sum:', sum(1)(2)(3)());

函数正在运行,我得到了正确的结果。但是,它会产生打字稿错误:This expression is not callable. Not all constituents of type 'number | ((_val: number | undefined) => number | ...)' are callable. Type 'number' has no call signatures.

如何在不使用 classthis 的情况下正确编写这样的 sum 函数?

您可以通过 function overloads:

精确描述函数行为来实现这一点
function sum(): number
function sum(val: number): typeof sum
function sum(val?: number): number | typeof sum {
  let internal = Number(val);
  if (val) {
    function sumup(): number
    function sumup(_val: number): typeof sumup
    function sumup(_val?: number): number | typeof sumup {
      if (_val && internal !== undefined) {
        internal += _val;
        return sumup;
      }
      return internal;
    };
    return sumup;
  }
  return internal;
};

console.log('sum:', sum(1)(2)(3)());

TypeScript playground