mardi 18 avril 2017

Typescript reflection inside a namespace

(Continuing on from previous discussion "Dynamically loading a typescript class (reflection for typescript)")

If I am already inside a namespace, is there a way to refer to classes inside the namespace for using 'reflection' to call their constructor?

namespace Test {

interface INamed {
    name:string;
}

class Foo implements INamed {
    name:string;
    constructor( name:string ) {
        this.name = name;
    }
}

class Bar implements INamed {
    name:string;
    constructor( name:string ) {
        this.name = name;
    }
}

export function factory( className:string ):INamed {
    var str = className + " instance";
    var t;
    /*                                                                                                                                                                     
    // how to 'reflect' inside namespace Test to get Test.Foo or Test.Bar?                                                                                                 
    t = new window[className]( str );                                                                                                                                      
    t = new context[className]( str );                                                                                                                                     
    t = new this.context[className]( str );                                                                                                                                
    t = new this[className]( str );                                                                                                                                        
    t = new Test[className]( str );                                                                                                                                        
    */
    t = new Bar( str );
    return t;
}

var bar = Test.factory( "Bar" );
console.log( bar.name );
}





Aucun commentaire:

Enregistrer un commentaire