【问题标题】:Type '<T>(array: T[], pred: (x: T) => boolean, index: number) => void' is not assignable to type '() => void'类型 '<T>(array: T[], pred: (x: T) => boolean, index: number) => void' 不可分配给类型 '() => void'
【发布时间】:2020-05-29 17:02:54
【问题描述】:

我正在尝试为 Array 创建一个扩展方法。

这是我创建的:

interface Array<T> {
    moveServiceBranchInArray(): void;
}

Array.prototype.moveServiceBranchInArray = function<T> (array: T[], pred: (x: T) => boolean, index: number): void 
{ 
    const curPos: number = array.findIndex(pred);
    index = Math.max(Math.min(index, array.length - 1), 0);

    if (curPos < 0) {
      return;
    }
    [array[curPos], array[index]] = [array[index], array[curPos]];
}

不幸的是,我收到了错误

"类型 '(array: T[], pred: (x: T) => boolean, index: number) => void' 不能分配给类型 '() => void'。"

如标题所示。什么给了,帮助表示赞赏。

【问题讨论】:

    标签: typescript extension-methods typescript-generics


    【解决方案1】:

    你的接口有一个不带参数的方法,因此是() =&gt; void,但在实现中你会得到一些参数,特别是签名(array: T[], pred: (x: T) =&gt; boolean, index: number) =&gt; void

    这正是编译器试图告诉你的。

    修复接口以使其与您的实现相匹配就足够了。

    【讨论】:

      【解决方案2】:

      你应该像这样在你的接口中指定函数参数:

      interface Array<T> {
          moveServiceBranchInArray(array: T[], pred: (x: T) => boolean, index: number): void;
      }
      
      Array.prototype.moveServiceBranchInArray = function<T> (array: T[], pred: (x: T) => boolean, index: number): void 
      { 
          const curPos: number = array.findIndex(pred);
          index = Math.max(Math.min(index, array.length - 1), 0);
      
          if (curPos < 0) {
            return;
          }
          [array[curPos], array[index]] = [array[index], array[curPos]];
      }
      

      【讨论】:

        猜你喜欢
        • 2021-11-16
        • 2017-07-29
        • 2021-11-16
        • 2021-10-04
        • 2016-07-31
        • 2017-01-05
        • 1970-01-01
        • 2021-12-05
        • 2017-12-29
        相关资源
        最近更新 更多