0

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?

5
  • Are you using a module system? That is, do you use import/export? Commented Jun 13, 2017 at 13:02
  • @NitzanTomer No I simply have this declaration in the same file that I am using it in. IntelliJ does not show any errors, but once I compile it I get the errors Commented Jun 13, 2017 at 13:03
  • @NitzanTomer, Actually I do have some imports at the top of the file. Does this change anything? Commented Jun 13, 2017 at 13:15
  • If you are using imports/exports then you do need to augment the global. I see that the error you're getting is 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? Commented Jun 13, 2017 at 13:22
  • @NitzanTomer, I was just about to post the code when I realised it was all my fault. I was indeed using an undefined array which is why I was getting the error. I believe this is the problem because it now seems to accept the code without any errors. Thanks Commented Jun 13, 2017 at 13:36

1 Answer 1

1

You only need to augment the global module when you are importing/exporting.

Because this is not your case, you just need to do this:

interface Array<T> {
    last(): T;
}

That is, don't wrap it with declare global { ... }.

Also, in the actual implementation, there's no need for generics, it can/should be:

if (!Array.prototype.last) {
    Array.prototype.last = function(): any {
        return this[this.length - 1];
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the quick response. I am now getting the following errors: Property 'last' does not exist on type 'string[]' and Property 'last' does not exist on type 'any[]'
The error is on anywhere I have Array.prototype.last and basically anywhere else I have used someArray.last()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.