【问题标题】:Typescript object extends the Array<BoxModel> can not call the inside methods anymoreTypescript 对象扩展了 Array<BoxModel> 不能再调用内部方法
【发布时间】:2017-09-03 17:40:27
【问题描述】:

升级到使用最新 Typescript 版本 (2.2.1) 的 Ionic3 后,我面临着一个大问题。我有一个普通的 Typescript 类 BoxList,它扩展了 Array。所以它是带有一些我使用的额外自定义方法的普通数组。我有一个名为“allHit”的方法,它遍历数组并返回布尔值。问题是,在 Ionic2 中一切正常,但升级后,我不能再调用 this.boxList.allHit 方法,因为它会抛出异常:

-> main.js:1 ERROR TypeError: this.boxList.allHit is not a function(...)

代码:

import {BoxModel} from "./BoxModel";
export class BoxList extends Array<BoxModel> {

    constructor() {
        super();
    }

    public allHit(boxTarget: BoxModel) : boolean {
        return this.findIndex(box => box.doesMatch(boxTarget) && !box.isHit) === -1;
    }

    public findUntouchedBox() : BoxModel {
        return this.find(box => !box.isHit);
    }
}

以及从其他对象调用 allHit 方法:

public allBoxesAreHit() : boolean {
    return this.boxList.allHit(this.targetBox);
}

有人知道这里发生了什么吗?谢谢!

【问题讨论】:

  • 你能把这个函数添加到你的问题中吗?
  • 嘿!我添加了整个班级。
  • 能否也添加函数调用?
  • 谢谢。还添加了函数调用。你知道这里出了什么问题吗?
  • 检查我的答案..它是打字稿更改..ionic 2 使用的是 2.0.9

标签: arrays typescript ionic2 extends


【解决方案1】:

根据 Typescript 2.1 breaking changes:

作为用 super(...) 调用返回的值替换 this 的值的一部分,子类化 Error、Array 和其他可能不再按预期工作。这是因为 Error、Array 等的构造函数使用 ECMAScript 6 的 new.target 来调整原型链;但是,在 ECMAScript 5 中调用构造函数时,无法确保 new.target 的值。

尝试他们的建议并设置:

constructor() { 
   super(); 
  Object.setPrototypeOf(this, BoxList.prototype); 
}

在构造函数中。

【讨论】:

  • 哇,这真的有效!我的构造函数现在看起来像这样:constructor() { super(); Object.setPrototypeOf(this, BoxList.prototype); }
  • Typescript 从 2.0.9 到 2.2.1 发生了很大变化。它是一个巨大的飞跃。你应该完成剩下的部分
猜你喜欢
  • 2012-07-05
  • 1970-01-01
  • 1970-01-01
  • 2014-07-08
  • 2019-12-16
  • 1970-01-01
  • 2018-02-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多