Is it possible to extend Array.prototype only for a specific type on typescript?

匿名 (未验证) 提交于 2019-12-03 01:45:01

问题:

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); }; 

is it possible to force this extension to be typed only for number?

回答1:

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);     }, }); 

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!