在运行时使用TypeScript获取对象的类/类型名称是否可行?
class MyClass{}
var instance = new MyClass();
console.log(instance.????); // Should output "MyClass"
在运行时使用TypeScript获取对象的类/类型名称是否可行?
class MyClass{}
var instance = new MyClass();
console.log(instance.????); // Should output "MyClass"
class MyClass {}
const instance = new MyClass();
console.log(instance.constructor.name); // MyClass
console.log(MyClass.name); // MyClass
但是请注意,在使用压缩代码时,名称很可能会有所不同。
let instance: any = this.constructor; console.log(instance.name);
- Subashany
的更简洁方法是console.log(instance.constructor['name']);
。 - Nick StrupatMyClass.name
将无法正常工作,因为它会将类的名称进行压缩。 - AngryHacker我的解决方案不是依赖于类名。object.constructor.name原理上可行。但如果你在像Ionic这样的TypeScript项目中使用,当进入生产环境时就会出问题,因为Ionic的生产模式会缩小JavaScript代码。所以类的名称会变成“a”和“e”之类的东西。
我最终做的是,在我所有的对象中都添加一个typeName类,构造函数将类名分配给它。所以:
export class Person {
id: number;
name: string;
typeName: string;
constructor() {
typeName = "Person";
}
是的,那并不是真正想要问的。但在可能被压缩的情况下使用 constructor.name 只会让人头痛。
let instance=new Person(); (instance.constructor.name==Person.name)
这段代码。两个名称都应该被压缩为相同的内容。 - Christopher Chasea
,b
,c
等,因此您不应依赖于此。 - tooleks我知道我来晚了,但我发现这也有效。
var constructorString: string = this.constructor.toString();
var className: string = constructorString.match(/\w+/g)[1];
或者...
var className: string = this.constructor.toString().match(/\w+/g)[1];
以上代码将整个构造函数代码作为字符串获取,并应用正则表达式以获取所有“单词”。第一个单词应该是“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"
Property 'name' does not exist on type 'Function'。
- orad(this as {}).constructor.name
或 (this as object).constructor.name
比 any
更好,因为你实际上可以获得自动完成 :-) - Simon_Weaver使用装饰器的解决方案,可在最小化/丑化后生存
我们使用代码生成来为实体类添加元数据,如下所示:
@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的polyfill。 getName() {
let comp:any = this.constructor;
return comp.name;
}
comp:any 是必需的,因为 TypeScript 编译器会发出错误,因为 Function 最初没有 name 属性。
element.nativeElement
的tagName
。在指令上,您可以像这样获取组件的名称:@Optional() element: ElementRef<HTMLElement>
,然后使用if (element != null && element.nativeElement.tagName.startsWith('APP-')) { this.name = element.nativeElement.tagName; }
。 - Simon_WeavermyClass.prototype.constructor.name
。myClass.constructor.name
,我会遇到TypeScript错误:error TS2339: Property 'name' does not exist on type 'Function'
。
public getClassName() {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec(this["constructor"].toString());
return (results && results.length > 1) ? results[1] : "";
}
我不知道从什么时候开始这是可能的,但现在它是:
class BeeKeeper {
hasMask: boolean;
}
class ZooKeeper {
nametag: string;
}
class Animal {
numLegs: number;
}
class Bee extends Animal {
keeper: BeeKeeper;
}
class Lion extends Animal {
keeper: ZooKeeper;
}
function createInstance<A extends Animal>(c: new () => A): A {
console.log(c.name) //this will give the class name
return new c();
}
createInstance(Lion).keeper.nametag;
createInstance(Bee).keeper.hasMask;
感谢本教程