是否可以仅针对打字稿上的特定类型扩展Array.prototype? [英] Is it possible to extend Array.prototype only for a specific type on typescript?
问题描述
我具有以下原型扩展,因为我一直在使用很多 reduce
:
I have the following prototype extension because I've been using a lot of reduce
:
declare interface Array<T> {
sum(): T;
}
Array.prototype.sum = function() {
return this.reduce((acc, now) => acc = acc + now, 0);
};
是否可以强制仅以数字键入此扩展名
?
推荐答案
在我写问题时,我终于找到了解决方法:
As I wrote the question, I ended up finding out how to do it:
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 = acc + now, 0);
},
});
还应注意,扩展基本原型通常不是一个好主意-如果基础更改了标准以实现新功能,您自己的代码库中可能会发生冲突。对于我特定代码库中的特定示例,我觉得很好,因为 sum
是一个描述性很强的方法名称,并且在多种语言中非常常见,因此将来的标准(可能)是具有兼容的实现。
It should also be noted that extending basic prototypes is usually not a good idea - in the event the base standard is changed to implement new functionality, there might be a conflict in your own code base. For this particular example on my particular codebase I feel it is fine, since sum
is a fairly descriptive method name and very common along multiple languages, so a future standard will (probably) have a compatible implementation.
这篇关于是否可以仅针对打字稿上的特定类型扩展Array.prototype?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!