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

class MyClass{}

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

当前回答

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

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”,第二个单词应该是类的名称。

希望这能有所帮助。

其他回答

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

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

首先需要将实例强制转换为any,因为Function的类型定义没有name属性。

class MyClass {
  getName() {
    return (<any>this).constructor.name;
    // OR return (this as any).constructor.name;
  }
}

// From outside the class:
var className = (<any>new MyClass()).constructor.name;
// OR var className = (new MyClass() as any).constructor.name;
console.log(className); // Should output "MyClass"

// From inside the class:
var instance = new MyClass();
console.log(instance.getName()); // Should output "MyClass"

更新:

使用TypeScript 2.4(可能更早),代码可以更清晰:

class MyClass {
  getName() {
    return this.constructor.name;
  }
}

// From outside the class:
var className = (new MyClass).constructor.name;
console.log(className); // Should output "MyClass"

// From inside the class:
var instance = new MyClass();
console.log(instance.getName()); // Should output "MyClass"

看这个问题。

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

我的解决方案是不依赖类名。Object.constructor.name在理论上是可行的。但如果你在Ionic这样的平台上使用TypeScript,一旦你进入生产模式,它就会陷入困境,因为Ionic的生产模式减少了Javascript代码。所以类被命名为“a”和“e”。

我最后做的是在我的所有对象中都有一个typeName类,构造函数将类名赋给它。所以:

export class Person {
id: number;
name: string;
typeName: string;

constructor() {
typeName = "Person";
}

是的,这不是问的,真的。但是将constructor.name用于将来可能会被最小化的东西上是在自找麻烦。

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

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

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

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

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