最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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

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

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

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

Share Improve this question edited Dec 29, 2020 at 19:25 Badashi asked Jan 2, 2018 at 13:28 BadashiBadashi 1,17010 silver badges18 bronze badges 1
  • Since the function sum will be available for all arrays regardless, why is this a useful thing to do? Wouldn't it make more sense to derive from Array instead? – T.J. Crowder Commented Jan 2, 2018 at 13:31
Add a ment  | 

1 Answer 1

Reset to default 8

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 + 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 mon along multiple languages, so a future standard will (probably) have a patible implementation.

发布评论

评论列表(0)

  1. 暂无评论