TypeScript中的通用类型反射

5
我可以在以下情况下确定通用类型T吗?
class MyClass {
    constructor() {
    }

    GenericMethod<T>(): string {
        return typeof(T);           // <=== this is flagged by the compiler,
                                    //      and returns undefined at runtime
    }
}

class MyClass2 {
}

alert(new MyClass().GenericMethod<MyClass2>());
1个回答

4
由于类型在编译时被擦除,因此在代码运行时不可用。这意味着您必须进行小型复制...
class MyClass {
    constructor() {
    }

    GenericMethod<T>(targetType: any): string {
        return typeof(targetType); 
    }
}

class MyClass2 {
}

alert(new MyClass().GenericMethod<MyClass2>(MyClass2));

在这种情况下,您得到的答案是function,但您可能想要的是MyClass2
我编写了一个如何在TypeScript中获取运行时类型名称的示例,它看起来像这样:
class Describer {
    static getName(inputClass) { 
        var funcNameRegex = /function (.{1,})\(/;
        var results = (funcNameRegex).exec((<any> inputClass).constructor.toString());
        return (results && results.length > 1) ? results[1] : "";
    }
}

class Example {
}

class AnotherClass extends Example {
}

var x = new Example();
alert(Describer.getName(x)); // Example

var y = new AnotherClass();
alert(Describer.getName(y)); // AnotherClass

这并没有回答问题。 - Michal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接