简体   繁体   中英

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

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM