I am trying to add a new method (last) to the Array class.
This is what I'm doing (amoung other functions declared) in my test.ts file:
declare global {
interface Array<T> {
last(): T;
}
}
if (!Array.prototype.last) {
Array.prototype.last = function <T>(): T {
return this[this.length - 1];
}
}
However this does not work as it seems to completely erase the other definitions for Array so now I get errors like:
TypeError: Cannot read property 'length' of undefined
This happens if I try to access the length property of any arrays.
How do I properly achieve this? Does the declaration have to go into a file by itself?
import/export?Cannot read property 'length' of undefined, it seems that the compiler thinks that your array doesn't exist at all. Can you add the code which generates this error?