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
?
-
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 fromArray
instead? – T.J. Crowder Commented Jan 2, 2018 at 13:31
1 Answer
Reset to default 8As 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.