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?

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

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'."
@seans One way to work around it would be to use type any instead of object like so: const run = (o:any) => {...}
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."
1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.