How to get the target class name from a generic instance?

Viewed 43

I have a generic service which saves data into a remote backend.

It can be generic because for each of my frontend entities (User, Group, ...) there is an endpoint "/api/user", "/api/group", so I can use the following method with success.

save<T extends Object>(clazz: { new(): T }, entity: T) {
    return fetch("/api/" + clazz.name.toLocaleLowerCase(),
      { body: JSON.stringify(entity)}
})

As you see the method take 2 parameters, the class and an instance of the class. I call it as following:

backendService.save(User, new User('Fractaliste'))

My question is: can I remove the first parameter? It is only used to extract the classname to build the api path. Can I extract the classname from the second parameter entity : T?

class TestClass {}
const x = new TestClass();


function save<T>(clazz: { new(): T }, entity: T) {

    console.log("From entity ", Object.getPrototypeOf(entity).constructor.name);
    console....

EDIT:

I test following code from @H.B. answer:

save<T>(clazz: { new(): T }, entity: T) {

    console.log("From entity ", Object.getPrototypeOf(entity).constructor.name);
    console.log("From clazz ", clazz.name);
}

And it gives to me:

enter image description here

Whereas from this official playground it should work... Any idea?

1 Answers

You probably could use constructor.name.

class TestClass {}
const x = new TestClass();
console.log(x.constructor.name)

Related