【问题标题】:Is it possible to extend Array.prototype only for a specific type on typescript?是否可以仅为打字稿上的特定类型扩展 Array.prototype?
【发布时间】:2018-06-12 05:09:39
【问题描述】:

我有以下原型扩展,因为我一直在使用很多reduce

declare interface Array<T> {
    sum(): T;
}

Array.prototype.sum = function() {
    return this.reduce((acc, now) => acc + now, 0);
};

是否可以强制只为number 键入此扩展名?

【问题讨论】:

  • 既然函数sum 无论如何都可用于所有数组,为什么这样做有用?从Array 派生不是更有意义吗?

标签: javascript arrays typescript generics


【解决方案1】:

当我写下这个问题时,我最终发现了如何去做:

declare interface Array<T> {
    sum(this: Array<number>): number;
}

Object.defineProperty(Array.prototype, 'sum', {
    value: function(this: Array<number>): number {
        return this.reduce((acc, now) => acc + now, 0);
    },
});

还应注意,扩展基本原型通常不是一个好主意 - 如果更改基本标准以实现新功能,您自己的代码库中可能会发生冲突。对于我的特定代码库中的这个特定示例,我觉得这很好,因为sum 是一个相当具有描述性的方法名称,并且在多种语言中非常常见,因此未来的标准将(可能)具有兼容的实现。

【讨论】:

  • 我不知道 javascript 类型的枚举,所以我做了一些研究,感谢您指出这一点。我更新了自己的答案。
  • FWIW,为了匹配其他函数值 Array.prototype 属性的配置方式,您需要在其中添加 writable: true, configurable: true
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-19
  • 1970-01-01
  • 2020-08-18
  • 1970-01-01
相关资源
最近更新 更多