typescript 如何获取打字稿的通用类<T>名称?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47312116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get Generic class<T> name of typescript?
提问by Shahin Al Kabir Mitul
My Generic class
我的通用类
export class BaseService<T> {
public subUrl;
constructor(public repo:RepogitoryService) { }
}
How can I store the class name of T on a local variable?
如何将 T 的类名存储在局部变量上?
回答by durisvk10
You must understand that Typescript is just a transpiler (compiler to javascript). Some of the syntax sugar (such as generics) are working only in type-checking phase (and also it's helpful for intellisense in your IDE/text-editor).
您必须了解 Typescript 只是一个转译器(编译器到 javascript)。一些语法糖(例如泛型)仅在类型检查阶段起作用(而且它对 IDE/文本编辑器中的智能感知很有帮助)。
However assignment to a variable is happening in runtime, in runtime it's just a plain Javascript. There are no types and no generics in runtime.
然而,对变量的赋值是在运行时发生的,在运行时它只是一个普通的 Javascript。运行时没有类型和泛型。
But here's the easiest way I would do it:
但这是我最简单的方法:
class Some<T> {
private TName : string;
constructor(x : T&Function) {
this.TName = x.name;
}
}
class Another {
}
const some = new Some<Another>(Another);
回答by Jules Randolph
You cannot, unfortunately. Typescript is a static type checker and has no support for type reflection at runetime such as java does. This is because its sources are transpiled to javascript.
不幸的是,你不能。Typescript 是一个静态类型检查器,不支持运行时的类型反射,如 java 那样。这是因为它的源代码被转换为 javascript。
However, there is hope for such support in the future, with a new typescript feature called "custom transformers". Those transformers are plugins that hook the transpilation process, opening the road to rich features regarding type reflection. A first example of such is ts-transformer-keys
.
但是,将来有希望提供此类支持,具有称为“自定义转换器”的新打字稿功能。这些转换器是挂钩转换过程的插件,为类型反射的丰富特性开辟了道路。第一个例子是ts-transformer-keys
。
回答by Yaremenko Andrii
回答by lolelo
Cast the object to Object
and get constructor name?
将对象投射到Object
并获取构造函数名称?
function nameOf(object: Object): string {
return object.constructor.name;
}