在 Typescript 中获取泛型类型的内部类型

Ric*_*ich 5 typescript

如何在 Typescript 中获取泛型类型的内部类型?那么TmyType<T>?

例如:

export class MyClass {
  myMethod(): Observable<{ prop1: string, ... }> {
    ....
  }
}

type myClassReturn = ReturnType<MyClass['myMethod']>;
// Sets the type to 'Observable<{ prop1: string, ... }>'. 
// How do I set this to just '{ prop1: string, ... }'?
Run Code Online (Sandbox Code Playgroud)

谢谢

Mac*_*ora 11

您可以使用infer关键字从泛型类型获取类型参数。考虑:

type GetInsideObservable<X> = X extends Observable<infer I> ? I : never;

// in your case it would be:
type A = GetInsideObservable<ReturnType<MyClass['myMethod']>> // { prop1: string, ... }
Run Code Online (Sandbox Code Playgroud)