0

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?

sean s
  • 45
  • 6
  • Does this answer your question? [Get an object's class name at runtime](https://stackoverflow.com/questions/13613524/get-an-objects-class-name-at-runtime) – Jeffrey Ram Aug 24 '22 at 01:41

2 Answers2

1

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

Jeffrey Ram
  • 1,132
  • 1
  • 10
  • 16
  • When I tested it in my test code(I've linked it in my question), it occur error as "Property 'name' does not exist on type 'object'." – sean s Aug 24 '22 at 02:21
  • @seans One way to work around it would be to use type `any` instead of `object` like so: `const run = (o:any) => {...}` – Jeffrey Ram Aug 24 '22 at 02:32
  • If you want it to work for both instances and non-instances, refer to @RahulSharma answer below. I excluded the solution for instances because you said "I'd like to get class name without instance." – Jeffrey Ram Aug 24 '22 at 02:42
0

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'
Rahul Sharma
  • 5,562
  • 4
  • 24
  • 48