Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending Array in TypeScript

Tags:

typescript

How to add a method to a base type, say Array? In the global module this will be recognized

interface Array {    remove(o): Array; } 

but where to put the actual implementation?

like image 635
Francois Vanderseypen Avatar asked Oct 09 '12 14:10

Francois Vanderseypen


1 Answers

You can use the prototype to extend Array:

interface Array<T> {     remove(o: T): Array<T>; }  Array.prototype.remove = function (o) {     // code to remove "o"     return this; } 

If you are within a module, you will need to make it clear that you are referring to the global Array<T>, not creating a local Array<T> interface within your module:

declare global {     interface Array<T> {         remove(o: T): Array<T>;     } } 
like image 110
Fenton Avatar answered Sep 21 '22 03:09

Fenton