【问题标题】:Is it possible to reuse type parameter of generics of some class是否可以重用某个类的泛型的类型参数
【发布时间】:2020-03-23 19:38:23
【问题描述】:

例如我有以下代码

    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);
      } 
    }

我可以获取 bar 的类型 - 但我想在不创建额外类型或接口的情况下获取 promise 中的类型。

我已经搜索了很多,我认为这还没有实现或建议,但在创建功能请求之前,我想确定一下。

【问题讨论】:

    标签: typescript generics types extraction


    【解决方案1】:

    你可以这样做,但是你需要一个条件类型来通过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);
        }
    }
    

    Playground Link

    【讨论】:

    • @Senyaak 您可以将代码移至参数:但a: Foo['bar'] extends Promise&lt;infer U&gt; ? U : never 不易阅读:typescriptlang.org/play/…
    • 我一直在寻找的东西。谢谢你。无论如何,我认为如果我们可以直接从泛型中提取类型将会很有用。
    • @Senyaak 如果Promise 有一个成员,例如结果,我们可以使用类型查询Foo['bar']['result']。所以对于一些泛型类你可以让它更简单,但对于Promise
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 2017-04-30
    • 2011-08-18
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多