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

class MyClass{}

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

当前回答

看这个问题。

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

其他回答

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

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

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

我知道我迟到了,但我发现这个方法也很有效。

var constructorString: string = this.constructor.toString();
var className: string = constructorString.match(/\w+/g)[1]; 

或者……

var className: string = this.constructor.toString().match(/\w+/g)[1];

上面的代码以字符串的形式获取整个构造函数代码,并应用正则表达式来获取所有的“words”。第一个单词应该是“function”,第二个单词应该是类的名称。

希望这能有所帮助。

简单的回答:

class MyClass {}

const instance = new MyClass();

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

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

完整的TypeScript代码

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

必须添加".prototype."来使用:myClass.prototype.constructor.name。 否则用下面的代码: myclass。constructor。name,我有TypeScript错误:

TS2339:属性“name”在类型“Function”上不存在。