Categories
TypeScript Answers

How to extend an array in TypeScript?

Spread the love

Sometimes, we want to extend an array in TypeScript.

In this article, we’ll look at how to extend an array in TypeScript.

How to extend an array in TypeScript?

To extend an array in TypeScript, we can add the method to Array.prototype and add the method to the Array interface.

For instance, we write

interface Array<T> {
  remove(o: T): Array<T>;
}

Array.prototype.remove = function (o) {
  // ...
  return this;
};

to add the remove method to the Array<T> interface.

Then we set Array.prototype.remove to a method that removes the entry from the current array, which is the value of this.

Then we return this which is the array without o.

If the code is in a module, we also need to add the remove property to the Array interface in a type declaration file.

For instance, in a .d.ts file, we write

declare global {
  interface Array<T> {
    remove(o: T): Array<T>;
  }
}

to add remove to it.

Conclusion

To extend an array in TypeScript, we can add the method to Array.prototype and add the method to the Array interface.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *