Home > Blockchain >  How to get class name without instance in Typescripts
How to get class name without instance in Typescripts

Time:08-24

I'd like to get class name without instance. But it does not work well. Here is my test code.

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)

How can I do?

CodePudding user response:

Use o.name instead of o.constructor.name

class User {
    id!:number;
    name!:string
}

const run = (o: any) => {
    console.log(o.name);
}

run(User); 

Source: Get an object's class name at runtime

CodePudding user response:

If o is an object use o.constructor.name otherwise 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'
  • Related