Reputation: 1183
is there a way to add a method sum()
to the Array
interface, but making it work for numbers only? (so that intellisense appears only when the array is Array<number>
).
Something like this:
declare global
{
interface Array<T extends number>
{
sum(): number;
}
}
(the above code actually does not work because the compiler expects Array<T>
)
Upvotes: 2
Views: 336
Reputation: 1183
I've ended using this solution, which does not provide intellisense but at least is able to catch errors at compile time. The trick is to use the this:
context for specifying the type of the array:
declare global {
interface Array<T> {
sum(this: Array<number>): number;
}
}
Array.prototype["sum"] = function(this: Array<number>) {
return this.reduce((previous, current) => previous + current, 0);
}
["a"].sum() // <- error: string[] is not assignable to number[]
Upvotes: 0
Reputation: 31600
Not by extending the interface, mainly because in javascript there are no generics and you can't add the sum method only in the case the array is of type number.
What you can do however is to create a new class that extends Array with the extra method.
It would look something like this:
class NumberArray extends Array<number> {
sum(): number {
return super.reduce((previous, current) => previous + current, 0);
}
}
let x: NumberArray = new NumberArray();
x.sum();
It may not be as clean as just adding a new method to the prototype but it's the next best thing.
You can see an example of it in the playground here.
Upvotes: 1