arrays - 在 Typescript 中扩展数组
问题描述
如果我尝试在Typescript 操场上这样做:
class Test extends Array {
constructor(items: number[]) {
super(...items);
}
foo(): void { console.log('foo'); }
}
const t = new Test([]);
t.foo();
这不起作用。foo
未定义。如果我查看生成的代码:
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var Test = /** @class */ (function (_super) {
__extends(Test, _super);
function Test(items) {
return _super.apply(this, items) || this;
}
Test.prototype.foo = function () { console.log('foo'); };
return Test;
}(Array));
var t = new Test([]);
t.foo();
该函数返回结果 of_super.apply
而不是this
。所以我最终得到一个数组,而不是一个继承自数组的测试。如果我改变这条线
return _super.apply(this, items) || this;
经过
_super.apply(this, items)
return this;
它按预期工作。由于 Array 的特殊性质,这可能是 Typescript 的错误吗?还是我的实现有问题?
解决方案
推荐阅读
- c# - 将每个列单元格值与一行中的下一个列单元格值进行比较
- php - 是否有任何选项可以根据 if 条件使用 eloquent 与关系?
- c - 如何将存储在另一个指针指向的地址的值分配给指向指针的地址?
- css - 如何将按钮与页面底部对齐
- javascript - 如何从外部 url (json) 读取数据并在另一个 html 页面中使用 javascript 打印它?
- javascript - 在 JavaScript 中使用空值对 JSON 数组进行排序
- flutter - 如何在 Flutter 中弹出没有动画的屏幕
- python - ModuleNotFoundError:没有名为“bs4”的模块/没有名为“请求”的模块
- shell - 在多行中分隔 sh 命令
- flutter - 如何使用没有OTP的电话号码将用户注册到firebase?