Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
117
rated 0 times [  118] [ 1]  / answers: 1 / hits: 33700  / 12 Years ago, sat, december 22, 2012, 12:00:00

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



For example, I have a JS function like this:



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 compiler asks me to define all Array interface properties. I know if I need this Xarray.prototype = new Array();, I have to extend Array in TS.



How to extend the JS native object in TS?


More From » typescript

 Answers
16

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!!!


[#81271] Thursday, December 20, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
devonw

Total Points: 311
Total Questions: 116
Total Answers: 111

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
;