TS 能否自动将 return 类型的函数泛型参数推断为 ReturnType<T>?
Can TS automatically infer return type of function generic parameter as ReturnType<T>?
我对打字稿推断 return 类型的函数泛型参数的方式感到有点困惑。在下面的示例中,我希望 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
拆分为两个通用参数、函数参数和 return 类型来解决,但我真的很想知道为什么函数泛型会这样。
当要推断的类型更简单时,编译器会做得更好。这种情况下的典型做法是将函数类型移至参数,如下所示:
const digest = <U,>(t: () => U) => {
const y = t();
return y;
}
相关:Is it possible to wrap a function and retain its types?
我对打字稿推断 return 类型的函数泛型参数的方式感到有点困惑。在下面的示例中,我希望 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
拆分为两个通用参数、函数参数和 return 类型来解决,但我真的很想知道为什么函数泛型会这样。
当要推断的类型更简单时,编译器会做得更好。这种情况下的典型做法是将函数类型移至参数,如下所示:
const digest = <U,>(t: () => U) => {
const y = t();
return y;
}
相关:Is it possible to wrap a function and retain its types?