Welcome Guest. Sign in or Signup


How to extend native JavaScipt object in TypeScript ?

Asked by: 9074 views 5.TypeScript


Sometimes we might what to inherit some property from native js function in TS, but in TS each and every JS object will be an interface so we can’t extend that to our own class. We can workaround to extend native JavaScipt object in TypeScript .

//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.

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

View on TypeScript Playground


  1. Irving Rodríguez on Dec 15, 2013 Reply


    How do i add rest methods of the Array?, for example: concat, splice, etcetera.


  2. RPW Verheij on Jan 03, 2014 Reply

    If I want to use this.splice in a function in YArray I get a compile error. Any suggestion to get arround this? I can’t seem to get anything with typecasting to work.

Comments on Question