BalaKrishnan웃 BalaKrishnan웃 - 6 months ago 357
Javascript Question

How to extend native JavaScript array in TypeScript

Is there any way to inherit a class from JS native function.

For (eg) i have js function like this in my js.

function Xarray()
{
Array.apply(this, arguments);
//some stuff for insert, add and remove notification
}
Xarray.prototype = new Array();


I tried to convert it to Typescript but i failed!!

export class Xarray implements Array {

}


the compailer ask me to define all Array Interface property, i know if need this
Xarray.prototype = new Array();
i have to extend Array in TS, how to extent the JS native object in TS?

Answer

I don't think there is a way to inherit existing interfaces like Array,

export class Xarray implements Array {

}

You should create a function and inherit it with its prototype. Typescript also will accept it which is similar to javascript.

function Xarray(...args: any[]): void; // required in TS 0.9.5
function Xarray()
{
    Array.apply(this, arguments);
   // some stuff for insert, add and remove notification
}
Xarray.prototype = new Array();

UPDATE: This one is discussed well and provided the best solution for this at jqfaq.com.

//a dummy class it to inherite array.
class XArray {
    constructor() {
        Array.apply(this, arguments);   
        return new Array();
    }
    // we need this, or TS will show an error,
    //XArray["prototype"] = new Array(); will replace with native js arrray function
    pop(): any { return "" };
    push(val): number { return 0; };
    length: number;
}
//Adding Arrray to XArray prototype chain.
XArray["prototype"] = new Array();

//our Class
class YArray extends XArray {
///Some stuff
}

var arr = new YArray();
//we can use the array prop here.
arr.push("one");
arr.push("two");

document.writeln("First Elemet in array : " + arr[0]);
document.writeln("</br>Array Lenght : " + arr.length);

Hope, this might help you!!!