James Mallon
James Mallon

Reputation: 1127

How do I retrieve the name of a generic class of type T in typescript

I am trying to implement the Service Locator pattern in TypeScript.

Here is my code:

 //due to only partial knowledge of TypeScript
  private static serviceMap: Map<string, any>;

  public static get<T>(): T {
    // firstly lazily register all of the necessary services if this is the
    // first time calling get.
    if(this.serviceMap == undefined){
      this.init();
    }
    let service = this.serviceMap.get(T.name) //issue
    if(service == undefined){
      throw Error("You must register the service before retrieving it.")
    }
    return service;
  }

The problem is on the line marked issue. As you can see I am trying to retrieve the name of the type of class that I am passing to the method. When I try and call T.name I get this error:

TS2693: 'T' only refers to a type, but is being used as a value here.

How can I retrieve the name of the class of type T.

I am very new to TypeScript so I apologise in advance if the answer is super simple.

Upvotes: 0

Views: 221

Answers (1)

robert
robert

Reputation: 6152

Service Locator's get method has to receive something based on which can locate the instance.

If you change the signature to this: public static get<T>(fn: Function): T {

then function type has a prop called name and you can use it inside get like this:

let service = Locator.serviceMap.get(fn.name);

The locator getting class instances can be called with:

const classInstance = Locator.get<ClassC>(ClassC);

Check this stackblitz.

Upvotes: 1

Related Questions