是否可以重用某些类的泛型的类型参数

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

例如,我有以下代码

    class Foo {
      bar: Promise<string[]>;

      // a is the same type as type of promise in bar 
      baz(a: ????): Foo['bar'] {
        // some code
        return Promise.resolve(a);
      } 
    }

我可以获取栏的类型-但我希望在promise中获取该类型而不创建额外的类型或接口。

我进行了很多搜索,我认为这尚未实现或建议,但是在确定功能请求之前,我想确定一下。

typescript generics types extraction
1个回答
1
投票

您可以这样做,但是您需要一个条件类型来通过infer从通用类中提取类型参数:

infer

type UnboxPromise<T extends Promise<any>> = T extends Promise<infer U> ? U : never; class Foo { bar: Promise<string[]>; // a is the same type as type of promise in bar baz(a: UnboxPromise<Foo['bar']>): Foo['bar'] { // some code return Promise.resolve(a); } }

© www.soinside.com 2019 - 2024. All rights reserved.