[英]Is it possible to extend Array.prototype only for a specific type on typescript?
我有以下原型扩展,因为我一直在使用很多reduce
:
declare interface Array<T> {
sum(): T;
}
Array.prototype.sum = function() {
return this.reduce((acc, now) => acc + now, 0);
};
是否可以强制只为number
输入此扩展名?
当我写这个问题时,我最终找到了如何去做:
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
是一个相当具有描述性的方法名称,并且在多种语言中非常常见,因此未来的标准将(可能)具有兼容的实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.