Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend native JavaScript array

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?

like image 589
BalaKrishnan웃 Avatar asked Dec 22 '12 06:12

BalaKrishnan웃


People also ask

Can you extend array in JavaScript?

You CANNOT extend the Array Object in JavaScript. Instead, what you can do is define an object that will contain a list of functions that perform on the Array, and inject these functions into that Array instance and return this new Array instance. What you shouldn't do is changing the Array.

How do you add an array to an array?

To append one array to another, use the push() method on the first array, passing it the values of the second array. The push method is used to add one or more elements to the end of an array. The method changes the contents of the original array. Copied!

What is extend in JavaScript?

The extends keyword is used to create a child class of another class (parent). The child class inherits all the methods from another class. Inheritance is useful for code reusability: reuse properties and methods of an existing class when you create a new class.


3 Answers

Starting in TypeScript 1.6, you can extend the Array type, see What's new in TypeScript

Here's an example:

class MyNewArray<T> extends Array<T> {     getFirst() {         return this[0];     } }  var myArray = new MyNewArray<string>(); myArray.push("First Element"); console.log(myArray.getFirst()); // "First Element" 

If you are emitting to ES5 or below, then use the following code:

class MyNewArray<T> extends Array<T> {     constructor(...items: T[]) {         super(...items);         Object.setPrototypeOf(this, MyNewArray.prototype);     }      getFirst() {         return this[0];     } } 

Read more about why this is necessary here.

like image 138
David Sherret Avatar answered Sep 18 '22 15:09

David Sherret


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

like image 42
Rajagopal 웃 Avatar answered Sep 19 '22 15:09

Rajagopal 웃


Yes it's possible to extend a native JS object in TS, however there is an issue extending built-in types (those included in lib.d.ts) like Array. Read this post for workaround: http://typescript.codeplex.com/workitem/4

So defining a type interface which extends a native type object at a later stage can be done in the following way:

/// <reference path="lib.d.ts"/>
interface Array {
    sort: (input: Array) => Array;
}

Using on a concrete example, you can sort some elements on an array which define a sort function in an interface and later implements it on an object.

class Math implements Array {
    sort : (x: Array) => Array {
          // sorting the array
    }
}
var x = new Math();
x.sort([2,3,32,3]);
like image 35
Endre Simo Avatar answered Sep 21 '22 15:09

Endre Simo