TypeScript 中的通用类型反射

che*_*ica 5 reflection typescript

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>());
Run Code Online (Sandbox Code Playgroud)

Fen*_*ton 4

由于类型在编译期间被擦除,因此在代码运行时它们不可用。

这意味着你必须做一个小的重复......

class MyClass {
    constructor() {
    }

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

class MyClass2 {
}

alert(new MyClass().GenericMethod<MyClass2>(MyClass2));
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您最终会得到答案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
Run Code Online (Sandbox Code Playgroud)