Search code examples
genericstypescriptreflectiontypescript2.0typename

Is it possible to get the type name of a generic type?


I have a method signature of execute<TResult>(): Observable<TResult>

How do I get the name of the TResult type?

Example:

execute<ViewModel> --> "ViewModel" is the result I need.


Solution

  • As far as I know it is not possible to get the name of TResult, but if you provide the accordingly constructor function you can get the name.

    Declaration:

    execute<TResult>(ctor: { new (): TResult }) : <TResult> {
      console.log(ctor.name) //Prints out SomeClass
      return <any>null;
    }
    

    Usage:

    execute<SomeClass>(SomeClass);