TypeScript Reflection

Topics: Language Specification
Dec 31, 2012 at 12:35 PM
Edited Jan 1, 2013 at 2:38 PM

While i can fully understand that there is no possibility to add true "reflection" support to typescript without generating a lot of code that would make output javascript less "comprehensive" and bigger; I do think that there is still some possibility of having some 'basic reflection' without too much effort.

For example one drawback of the prototype based inheritance is the fact that you never really know class hierarchy used to create an object ( you could know it with __proto__ but it is not supported by all browsers).
Since with typescript inheritance is achieved by the __extends function, why not injecting a property referencing base class in the sub class, for example :


class A { }
class B extends A { }


Would be translated to :


var __extends = this.__extends || function (d, b) {
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
    d.__baseClass__ = b;
var A = (function () {
    function A() { }
    return A;
var B = (function (_super) {
    __extends(B, _super);
    function B() {
        _super.apply(this, arguments);

    return B;

So with 'constructor' and  '__baseClass__' we would be able to access the whole inheritance chain.

Jan 3, 2013 at 4:03 PM

This kind of modification should be pretty easy to do (my guess is that it would go in emitJavascriptClass in emitter.ts).  In general, we wouldn't want to add this because we try to keep codegen to an absolute minimum (keeping as close to the original JavaScript as possible).  Also in general, reflection would need to cover more than just whether or not a class extends another, but also what its shape is.  This would work for some things, but not (I believe) for functions.