我有一个泛型函数,我想获取传入的类的名称。
public addComponent<T extends Component>(): Component {
comp = new Component() as T;
comp.name = T.constructor.name;
console.log(comp.name);
return comp;
}
然后我可以这样称呼它:
obj.addComponent<MyClass>();
我希望日志显示&#34; MyClass&#34;。但目前我收到一个错误说:
找不到姓名&#39; T&#39;。
答案 0 :(得分:2)
没有办法做到这一点。
T
在运行时不存在,它仅用于编译,编译器会删除它(以及类型),因此生成的javascript为:
class MyFactory {
public addComponent<T extends Component>(): Component {
let comp = new Component() as T;
comp.name = T.constructor.name;
console.log(comp.name);
return comp;
}
}
时:
var MyFactory = (function () {
function MyClass() {
}
MyFactory.prototype.addComponent = function () {
var comp = new Component();
comp.name = T.constructor.name;
console.log(comp.name);
return comp;
};
return MyFactory;
}());
正如您所看到的,js代码不具有泛型签名,因此T
没有定义,因此T.constructor
会导致错误#39} ;重新接受。
如果您希望该方法通过传递它来创建类的实例,那么它应该如下所示:
interface ComponentConstructor<T extends Component> {
new(): T;
name: string;
}
class Component {
name: string;
}
class MyComponent extends Component {}
class MyFactory {
public addComponent<T extends Component>(ctor: ComponentConstructor<T>): Component {
let comp = new ctor();
comp.name = ctor.name;
console.log(comp.name);
return comp;
}
}
let factory = new MyFactory();
let obj = factory.addComponent(MyComponent as ComponentConstructor<MyComponent>);