命名空间内的Typescript反射

时间:2017-04-19 05:51:27

标签: typescript reflection

(继续前一次讨论"Dynamically loading a typescript class (reflection for typescript)"

如果我已经在命名空间内,有没有办法引用命名空间内的类来使用' reflection'打电话给他们的构造函数?

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;
}
}

然后(不得不拆掉它以便SO不会失去它,无论如何)

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

1 个答案:

答案 0 :(得分:1)

哈,问这个问题让我看到了光明。我认为。诀窍是导出类,呃。

namespace Test {

interface INamed {
    name:string;
}

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

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

export function factory( className:string ):INamed {
    return new Test[className]( className + " instance" );
}

}

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