打字稿:通用T的字符串表示形式

时间:2019-10-11 15:36:30

标签: typescript typescript-generics

我想创建一个通用方法,该方法可以接收通用<T>,并且我需要使用方法内的<T>字符串

我们使用传递实体名称作为参数的API:http://server/api/fetch/Entity/123

我需要知道<T>是:

    public get<T>() {
        const response = super.doRequest("/api/fetch/<T>/123");
        return response as T;
    }

当我调用该方法时,我知道我在寻找什么(JobView):

    this.baseService.get<JobView>();

1 个答案:

答案 0 :(得分:1)

当编译器发出JavaScript时,类型系统完全为erased。运行时没有T。相反,您必须将实际的字符串值传递给get()方法。

如果从传递给doRequest()的实体名称到实体类型进行映射,则可以得到一些智能键入。例如:

interface EntityMap {
    JobView: JobView;
    OtherEntity: OtherEntity;
    EtCetera: EtCetera;
}

在运行时不需要EntityMap类型的任何对象;它只是编译器用来了解名称"JobView"对应于类型JobView的帮助程序类型。从名称到类型的映射是接口很好的事情,所以这就是我们使用它的原因。


然后,您的get()方法可能如下所示:

public get<K extends keyof EntityMap>(entityName: K) {
    const response = super.doRequest("/api/fetch/" + entityName + "/123");
    return response as EntityMap[K];
}

因此,您传递的通用类型为entityName的{​​{1}}参数必须与K ...即keyof EntityMap"JobView"或{{ 1}}。因此,现在在运行时,值"OtherEntity"可用于调用"EtCetera"。然后,响应将以类型entityName的形式返回,我们在doRequest()中以look up EntityMap[K]命名的属性。因此您可以像这样使用它:

K

,您将看到调用EntityMap时,编译器将返回类型为const r = new RequestyThing(); const jv = r.get("JobView"); // const jv: JobView 的值。

希望有帮助。祝你好运!

Link to code