【发布时间】:2022-01-10 17:28:14
【问题描述】:
我对 typescript 推断函数泛型参数的返回类型的方式有点困惑。在下面的示例中,我希望 digest1 中的 x 具有 ReturnType<T> 类型,但它是 any。
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