0

Currently I am trying to write a prototype extension function. But it seems that nothing what I try works. Have for that reason also tried examples from others but they all give the same error:

TypeError: array.remove is not a function

Here is some code I put in my generic-utill file:

    export {};
    declare global {
        interface Array<T> {
            remove(elem: T): Array<T>;
        }
    }
    
    Array.prototype.remove = function<T>(elem: T): T[] {
        return this.filter(e => e !== elem);
    };

And this in my test for the generic utill:

    describe('generic-util', () => {
        describe('Array', () => {
            it('should return array correctly using remove', async () => {
                const array = [1, 2, 3, 4];
                const result = array.remove(4);

                expect([1, 2, 3]).toStrictEqual(result);
            });
        });
    });

Could someone maybe explain what I am doing wrong since I don't really understand what I am missing.

MrAndre
  • 811
  • 1
  • 10
  • 26
  • As a side note, it is recommended to not modify the prototypes of the JavaScript classes. – axiac Feb 02 '23 at 18:00
  • @axiac What would be the recommended way to extend such classes? First time that I see that it is not recommended to use prototypes as such (am new to Typescript) – MrAndre Feb 02 '23 at 18:07
  • 1
    ^ https://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice – jcalz Feb 02 '23 at 18:11
  • `Array` is a standard JavaScript class. It is [documented](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array) and it behaves as it is described in the documentation. Changing its methods can be confusing for your co-workers and can be a source of hidden bugs. – axiac Feb 02 '23 at 18:12
  • I expect that the issue here (leaving aside why it's a Bad Idea to mess with native prototypes) is that your service class file is not importing your generic util file, so the code in that util file never runs. But without a [mre] I can easily test myself this is just a guess – jcalz Feb 02 '23 at 18:13
  • @jcalz Updated my question and added a test which is in the same directory as my generic-utill.ts – MrAndre Feb 02 '23 at 20:15
  • 2
    That doesn't mean it's being loaded; file system adjacency is insufficient. – Dave Newton Feb 02 '23 at 20:22

0 Answers0