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

class MyClass{}

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

当前回答

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

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

其他回答

看这个问题。

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

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

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

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

使用装饰器的解决方案,在缩小/丑陋化中幸存

我们使用代码生成用元数据来装饰我们的实体类,如下所示:

@name('Customer')
export class Customer {
  public custId: string;
  public name: string;
}

然后使用以下助手进行消费:

export const nameKey = Symbol('name');

/**
 * To perserve class name though mangling.
 * @example
 * @name('Customer')
 * class Customer {}
 * @param className
 */
export function name(className: string): ClassDecorator {
  return (Reflect as any).metadata(nameKey, className);
}

/**
 * @example
 * const type = Customer;
 * getName(type); // 'Customer'
 * @param type
 */
export function getName(type: Function): string {
  return (Reflect as any).getMetadata(nameKey, type);
}

/**
 * @example
 * const instance = new Customer();
 * getInstanceName(instance); // 'Customer'
 * @param instance
 */
export function getInstanceName(instance: Object): string {
  return (Reflect as any).getMetadata(nameKey, instance.constructor);
}

额外信息:

您可能需要安装reflect-metadata reflect-metadata是由TypeScript成员为提议的ES7 Reflection API编写的填充 JS中关于装饰器的建议可以在这里找到

首先需要将实例强制转换为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代码

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