从TypeScript扩展数组 [英] Extending Array from TypeScript
问题描述
我在下面的代码中做错了什么?
What Am I doing wrong in my below code?
我正在尝试在我的班级上扩展数组
MyNumberList
然后尝试使用它。我看到的是,似乎没有任何项目被添加到列表中。当我尝试访问列表元素时,我得到 undefined
。
I am trying to extend Array
on my class MyNumberList
and then trying to use it. What I see is that no items seem to be getting added to the list. I get an undefined
when I attempt to access the list elements.
PS我正在使用TypeScript 1.8.2
P.S I am using TypeScript 1.8.2
class MyNumberList extends Array<number> {
constructor(...numbers: number[]) {
// looks like this is not working
super(...numbers);
}
}
let statusCodes: MyNumberList = new MyNumberList(10, 20, 30);
console.log(statusCodes[0]); // printing undefined
console.log(statusCodes.length); // printing 0
推荐答案
无法在ES5中扩展数组,所以TypeScript编译器生成的代码无法正常工作。它为你的构造函数生成的代码是:
Arrays cannot be extended in ES5, so the code that the TypeScript compiler produces doesn't work correctly. The code it produces for your constructor is this:
function MyNumberList() {
var numbers = [];
for (var _i = 0; _i < arguments.length; _i++) {
numbers[_i - 0] = arguments[_i];
}
_super.apply(this, numbers);
}
...其中 _super
是数组
。在正常情况下, _super.apply(this,numbers)
可以正常工作,但是 Array
函数当它被称为函数时,它的行为与它被称为构造函数时的行为不同。 Babel和其他ES2015(ES6)到ES5的转发器也存在同样的问题。要从数组中正确继承,需要JavaScript引擎中仅在ES5引擎中不存在的功能。
...where _super
is Array
. In the normal course of things, _super.apply(this, numbers)
would work just fine, but the Array
function behaves differently when it's called as a function than when it's called as a constructor. Babel and other ES2015 (ES6) to ES5 transpilers have the same problem. To properly inherit from an array requires features within the JavaScript engine that just are not present in ES5 engines.
如果将构造函数代码更改为:
If you change your constructor code to:
constructor(...numbers: number[]) {
super();
this.push(...numbers);
}
...它会正确填充你的实例。不过,我不能保证 Array
的其他功能有多好。
...it will populate your instance correctly. I can't guarantee how well other features of Array
will work, though.
这篇关于从TypeScript扩展数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!