是否有可能在运行时使用TypeScript获得对象的类/类型名?

class MyClass{}

var instance = new MyClass();
console.log(instance.????); // Should output "MyClass"

当前回答

看这个问题。

因为TypeScript被编译成JavaScript,所以在运行时你运行的是JavaScript,所以同样的规则也适用。

其他回答

看这个问题。

因为TypeScript被编译成JavaScript,所以在运行时你运行的是JavaScript,所以同样的规则也适用。

简单的回答:

class MyClass {}

const instance = new MyClass();

console.log(instance.constructor.name); // MyClass
console.log(MyClass.name);              // MyClass

但是,要注意,在使用简化代码时,名称可能会有所不同。

如果您已经知道预期的类型(例如,当一个方法返回联合类型时),那么您可以使用类型保护。

例如,对于基本类型,你可以使用typeof守卫:

if (typeof thing === "number") {
  // Do stuff
}

对于复杂类型,你可以使用一个instanceof guard:

if (thing instanceof Array) {
  // Do stuff
}

完整的TypeScript代码

public getClassName() {
    var funcNameRegex = /function (.{1,})\(/;
    var results  = (funcNameRegex).exec(this["constructor"].toString());
    return (results && results.length > 1) ? results[1] : "";
}

在Angular2中,这可以帮助获取组件名称:

    getName() {
        let comp:any = this.constructor;
        return comp.name;
    }

comp:any是必需的,因为TypeScript编译器会报错,因为Function最初没有属性名。