【问题标题】:Can TS automatically infer return type of function generic parameter as ReturnType<T>?TS 能否自动推断函数泛型参数的返回类型为 ReturnType<T>?
【发布时间】:2022-01-10 17:28:14
【问题描述】:

我对 typescript 推断函数泛型参数的返回类型的方式有点困惑。在下面的示例中,我希望 digest1 中的 x 具有 ReturnType&lt;T&gt; 类型,但它是 any

Playground

    type Base = () => any;

    // this function returns any
    const digest1 = <T extends Base>(t: T) => {
        const x = t();
        return x;
    }

    // but i expect it to behave like this, without assertions
    const digest2 = <T extends Base>(t: T) => {
        const y = t() as ReturnType<T>;
        return y;
    }

这是预期的行为吗?有没有一种很好的方法来解决这个问题,而不用手动断言 as 关键字,但仍然使用函数泛型参数(可能有一些配置)?

我知道,这可以通过将 T 拆分为两个泛型参数、函数参数和返回类型来解决,但我真的很想知道为什么函数泛型会这样。

【问题讨论】:

    标签: typescript types


    【解决方案1】:

    当要推断的类型更简单时,编译器会做得更好。这种情况下的典型方法是将函数类型移动到参数中,如下所示:

    const digest = <U,>(t: () => U) => {
        const y = t();
        return y;
    }
    

    相关:Is it possible to wrap a function and retain its types?

    【讨论】:

      猜你喜欢
      • 2020-01-23
      • 2019-02-17
      • 2020-03-12
      • 1970-01-01
      • 2022-11-05
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      • 2016-07-23
      相关资源
      最近更新 更多