typescript - 扩展数组 <number>

标签 typescript

为什么以下没有按预期工作:

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/

相关文章:

typescript - typescript 枚举的 vue v-for

date - Typescript 认为 getYear 在 Date 类型上不存在

angular - 如何在代码中创建 Angular 模板引用

typescript - 如何扩展返回类型?

node.js - 此模块使用 'export =' 声明,并且只能在使用 'esModuleInterop' 标志时与默认导入一起使用

javascript - 将 Typescript 转译为纯 Javascript

typescript - Jest + Vue - 语法错误 : Unexpected token <

typescript :函数声明中接口(interface)属性的类型安全

在 AppModule 加载之前 Angular 加载外部配置

typescript - 在 typescript 中定义对象形状变体