Badashi
Badashi

Reputation: 1170

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?

Upvotes: 5

Views: 2534

Answers (1)

Badashi
Badashi

Reputation: 1170

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.

Upvotes: 8

Related Questions