typescript 在运行时获取对象的类名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13613524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 00:56:53  来源:igfitidea点击:

Get an object's class name at runtime

typescript

提问by Adam Mills

Is it possible to get an object's class/type name at runtime using TypeScript?

是否可以在运行时使用 TypeScript 获取对象的类/类型名称?

class MyClass{}

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

回答by Mikael Couzic

Simple answer :

简单的回答:

class MyClass {}

const instance = new MyClass();

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

However: beware that the name will likely be different when using minified code.

但是:请注意,使用缩小代码时名称可能会有所不同。

回答by Adam Mills

I know I'm late to the party, but I find that this works too.

我知道我参加聚会迟到了,但我发现这也有效。

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

Alternatively...

或者...

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

The above code gets the entire constructor code as a string and applies a regex to get all 'words'. The first word should be 'function' and the second word should be the name of the class.

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

Hope this helps.

希望这可以帮助。

回答by Matt Burland

See this question.

看到这个问题

Since TypeScript is compiled to JavaScript, at runtime you are running JavaScript, so the same rules will apply.

由于 TypeScript 被编译为 JavaScript,因此在运行时您正在运行 JavaScript,因此将适用相同的规则。

回答by SonOfALink

My solution was not to rely on the class name. object.constructor.name works in theory. But if you're using TypeScript in something like Ionic, as soon as you go to production it's going to go up in flames because Ionic's production mode minifies the Javascript code. So the classes get named things like "a" and "e."

我的解决方案是不依赖类名。object.constructor.name 理论上有效。但是如果你在 Ionic 之类的东西中使用 TypeScript,一旦你进入生产环境,它就会火上浇油,因为 Ionic 的生产模式会缩小 Javascript 代码。所以这些类被命名为“a”和“e”。

What I ended up doing was having a typeName class in all my objects that the constructor assigns the class name to. So:

我最终做的是在构造函数将类名分配给的所有对象中都有一个 typeName 类。所以:

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

constructor() {
typeName = "Person";
}

Yes that wasn't what was asked, really. But using the constructor.name on something that might potentially get minified down the road is just begging for a headache.

是的,这不是被问到的,真的。但是在将来可能会被缩小的东西上使用constructor.name 只会让人头疼。

回答by Westy92

You need to first cast the instance to anybecause Function's type definition does not have a nameproperty.

您需要先将实例转换为 ,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"

Update:

更新:

With TypeScript 2.4 (and potentially earlier) the code can be even cleaner:

使用 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"

回答by Flox

  • Had to add ".prototype." to use : myClass.prototype.constructor.name.
  • Otherwise with the following code : myClass.constructor.name, I had the TypeScript error :
  • 必须添加“ .prototype.”才能使用:myClass.prototype.constructor.name
  • 否则使用以下代码: myClass.constructor.name,我有 TypeScript 错误:

error TS2339: Property 'name' does not exist on type 'Function'.

error TS2339: Property 'name' does not exist on type 'Function'.

回答by Nati Krisi

The full TypeScript code

完整的 TypeScript 代码

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

回答by Admir Sabanovic

In Angular2 this can help to get components name:

在 Angular2 中,这有助于获取组件名称:

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

comp:anyis needed because TypeScript compile will issue errors since Function initially does not have property name.

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

回答by Cocowalla

If you already know what types to expect (for example, when a method returns a union type), then you can use type guards.

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

For example, for primitive types you can use a typeof guard:

例如,对于原始类型,您可以使用typeof guard

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

For complex types you can use an instanceof guard:

对于复杂类型,您可以使用instanceof guard

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