简体   繁体   中英

How to get the type of T inside generic method in Typescript?

I have a generic method in a class.,

export class BaseService {
    public getAll<T>(): Observable<T> {
        // get type of T

        // const type = typeof(T); // Tried this but getting compilation exceptions 

        return this.http.get<T>(this.actionUrl + 'getAll');
    }
}

I'll be calling the method like below, from few other typescript classes.

this.service.getAll<SubscriberData>().subscribe(response => {
      // Response
    }, error => {
      console.log(error);
    }, () => {
      // do something commonly
    });

When i tried this getting the following exception

const type = typeof(T); 

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

Edit:

I'm trying to get the type of a class which is calling the generic method. For Ex: getAll<SubscriberData> i want to get the type SubscriberData inside that method.

How can i do this?

You can access the constructor reference of a class in a class decorator, a property in a property (or accessor) decorator, or a parameter in a parameter decorator (using reflect-metadata ).

Unfortunately, generic type arguments are not available at runtime this way, they'll always yield the runtime equivalent of a simple Object type.

Instead, you can supply the constructor reference, which you can also use to infer the generic type (ie instead of specifying the generic type, you specify the corresponding constructor reference of that generic type):

export class BaseService {
    public getAll<T>(TCtor: new (...args: any[]) => T): Observable<T> {
        // get type of T
        const type = typeof(TCtor);

        // ...
    }
}

And then use it like this:

new BaseService().getAll(DataClass); // instead of 'getAll<DataClass>()'

Demo on playground

The type new (...args: any[]) => T simply says: a newable type (ie a class/constructor) that returns the generic T type (in other words, the corresponding class/constructor for the generic T instance type).

Thanks a lot! This is the only option I found online. I don't know why cant they implement this functionality in some common library

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