3

我正在尝试在 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.

sum在不使用classor的情况下如何正确编码这样的函数this

4

1 回答 1

3

您可以通过使用函数重载精确描述函数行为来实现这一点:

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 游乐场

于 2022-02-18T13:06:51.173 回答