繁体   English   中英

如何在 Typescripts 中获取没有实例的 class 名称

[英]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); 

来源: 在运行时获取对象的 class 名称

如果oobject使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM