[英]How to get class name without instance in Typescripts
我想在没有实例的情况下获得 class 名称。 但它不能很好地工作。 这是我的测试代码。
class User {
id!:number;
name!:string
}
//It should use object type. Not used User type directly.
const run = (o:object) => {
console.log(o.constructor.name);
}
run(User);
//It printed as Function.
//But, I'd like to class name(aka, User) without instance(new User)
我能怎么做?
使用o.name
而不是o.constructor.name
class User {
id!:number;
name!:string
}
const run = (o: any) => {
console.log(o.name);
}
run(User);
如果o
是object
使用o.constructor.name
否则o.name
。
class User {
public name: string;
constructor(name: string) {
this.name = name;
}
}
const run = (o: any) => {
typeof o === 'object' ? console.log(o.constructor.name) : console.log(o.name);
}
run(User); // 'User'
run(new User('john doe')); // 'User'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.