Manish Shrotriya Manish Shrotriya - 2 months ago 5
TypeScript Question

Typescript doesn't add prototype.constructor during transpilation

Following is TS class.

class TestA {
name: string;

constructor(name:string){
this.name = name;
}

getName(): string {
return this.name;
}

getCName(): string {
return TestA.prototype.constructor.name;
}
}

let ta = new TestA('ta');


And below is the transpiled JS

var TestA = (function () {
function TestA(name) {
this.name = name;
}
TestA.prototype.getName = function () {
return this.name;
};
TestA.prototype.getCName = function () {
return TestA.prototype.constructor.name;
};
return TestA;
}());
var ta = new TestA('ta');
//# sourceMappingURL=TestA.js.map


Issue: 1:
As one can see there is no constructor property set on TestA prototype. In my application I need it. I am using inheritance and knowing the type of of object is vital as I am converting class objects to and from JSON. Could you please suggest me any tweak to TS compiler that can do it.

Otherwise I will have to manually set it for every class that I create.

Issue 2:

In the generated JS all functions are anonymous. Is there a way to give them name like . This is also extremely helpful during debugging. Could any one suggest me a way to do it too.

Thanks for reading and taking interest in the post.
-Manish

Answer

The constructor in ES5 is the function:

function TestA(name) {
    this.name = name;
}

The constructor keyword was added in ES6 and therefor not used when transpiling to ES5.

Comments