Skip to content Skip to sidebar Skip to footer

How Does Extends In TypeScript Work?

The following TypeScript code: class BaseClassWithConstructor { private _id: number; constructor(id: number) { this._id = id; } } class DerivedClassWithConstru

Solution 1:

Until ECMAScript support for classes goes native, the extends function polyfills the expected behaviour of inheritance.

If you are used to the normal JavaScript prototypical inheritance, you'll be wondering why it isn't just doing the __.prototype = b.prototype; part. If so, you'll be interested to know that the addition of for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; means that static members will be copied too. For example...

class BaseClassWithConstructor {
    private _id: number;
    constructor(id: number) {
        this._id = id;
    }

    static doIt() {
        alert('Done it');
    }
}

class DerivedClassWithConstructor extends BaseClassWithConstructor {
    private _name: string;
    constructor(id: number, name: string) {
        this._name = name;
        super(id);
    }
}

DerivedClassWithConstructor.doIt();

Solution 2:

The generated javascript code can be divided in two parts:

for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];

is for "inheriting" the static properties of base class. Actually in the newest version of type script, this line of code has been substituted with

extendStatics(d, b);

where the definition of extendStatics is:

var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };

The only difference is that in new version, manipulation of [[prototype]] is used if related behavior is supported by browsers, otherwise fallback to the old practice, i.e. copying every owned property from base class to derived class.


And as for

function __() { this.constructor = d; } __.prototype = b.prototype; d.prototype = new __();

It is really a slightly fancier way of setting the prototype of d to a new instance of b. But instead of directly assigning new b(...) to d.instance, a dummy constructor __ is used since for the purpose of setting prototype, we don't need the constructor b to be really invoked, and by using dummy function, we don't need to pass arguments to the constructor. See this SO answer.


Post a Comment for "How Does Extends In TypeScript Work?"