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.