简体   繁体   English

泛型获取类名

[英]Generics get class name

I have a generic function that I would like to get the name of the class that is passed in. 我有一个通用函数,我想获取传入的类的名称。

public addComponent<T extends Component>(): Component {
    comp = new Component() as T;
    comp.name = T.constructor.name;
    console.log(comp.name);
    return comp;
}

Then lets say I call it like so: 然后说我这样称呼它:

obj.addComponent<MyClass>();

I would then expect the log to display "MyClass". 然后,我希望日志显示“ MyClass”。 But currently I get an error saying: 但是目前我收到一条错误消息:

Cannot find name 'T'. 找不到名称“ T”。

There's no way to do that. 无法做到这一点。

The T doesn't exist at runtime, it's only for compilation and the compiler removes that (along with the types) so the resulting javascript for this: T在运行时不存在,仅用于编译,并且编译器会删除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;
    }
}

Is: 方法是:

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

As you can see, the js code doesn't have the generics signature, so there's no definition for T , and so T.constructor results in the error you're receiving. 如您所见,js代码没有泛型签名,因此没有T的定义,因此T.constructor导致您收到错误。

If you want the method to create an instance of a class by passing it then it should look like: 如果您希望该方法通过传递类来创建类的实例,则它应类似于:

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

( code in playground ) 操场上的代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM