TypeScript 中的泛型类型反射 [英] Generic type reflection in TypeScript

查看:61
本文介绍了TypeScript 中的泛型类型反射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在以下场景中确定泛型类型 T 吗?

Can I determine the generic type T in the following scenario?

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>());

推荐答案

因为类型在编译时被擦除,所以在代码运行时不可用.

Because the types are erased during compilation, they are not available when the code runs.

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

This means you have to make a small duplication...

class MyClass {
    constructor() {
    }

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

class MyClass2 {
}

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

在这种情况下,您最终会得到答案 function,但您可能想要 MyClass2.

In this case, you end up with the answer function, but you probably wanted MyClass2.

我写了一个 如何在 TypeScript 中获取运行时类型名称的示例,如下所示:

I have written an example of how to get runtime type names in TypeScript, which looks like this:

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

这篇关于TypeScript 中的泛型类型反射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆