简体   繁体   中英

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM