在打字稿中获取通用类型的内部类型

问题描述 投票:0回答:1

如何在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, ... }'?

谢谢

typescript
1个回答
0
投票

您可以使用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, ... }
© www.soinside.com 2019 - 2024. All rights reserved.