为什么以下没有按预期工作:
class MyArray extends Array<number>
{
constructor(n: number)
{
super(n);
}
}
function initalize()
{
var myArray = new MyArray(4);
var l = myArray.length; // l should be 4
}
"l"结果是 0,而不是我预期的 4。是否在“MyArray”中实现构造函数都没有关系。
最佳答案
您的代码转换为
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var MyArray = (function (_super) {
__extends(MyArray, _super);
function MyArray(n) {
_super.call(this, n);
}
return MyArray;
})(Array);
function initalize() {
var myArray = new MyArray(4);
var l = myArray.length; // l should be 4
}
问题是您不再处理具有特殊属性的原始 native 类型。因此,您的扩展类型 - 即使您会成功 - 也会受到严重限制并让其他人感到困惑。
详细信息和陷阱可以在 Axel Rauschmayer 的文章中找到:http://www.2ality.com/2013/03/subclassing-builtins-es6.html
关于typescript - 扩展数组 <number>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35334547/