I can get the name of an object like so:
let name = obj.prototype.constructor.name;
But what I want to do is get the name of the generic type in my generic Angular service.
@Injectable({
providedIn: 'root'
})
export class MyService<T> {
private _value: T;
constructor(){}
//... other methods
private error(error: any)
{
console.log(`Error for service type: ${_value.prototype.constructor.name}`)
}
}
_value.prototype.constructor.name
doesn't work, prototype doesn't exist for type T.
I have seen the typescript specific posts that state this is only possible if the constructor takes a parameter of the type because once transpiled type declarations are removed as they don't exist in javascript.
As angular is creating this service via dependency injection what is the proper way to pass the type so it can be instantiated in a way that allows me to read the name as a string?
I have seen in this post: How to get name of generic type T inside service in Angular
It says to use this function:
function createInstance<T>(type: new() => T): T {
return new type();
}
But I cannot see how I am supposed to use this function in relation to my angular service above.
How do I get the string inside the service?