TypeScript 在类型构造函数中推断回调返回类型

2024-03-31

我想为接收类型的函数编写一个类型构造函数S和一个函数S到另一种类型,然后将该函数应用于S并返回结果:

// This works but it's tied to the implementation
function dig<S, R>(s: S, fn: (s: S) => R): R {
  return fn(s);
}

// This works as separate type constructor but I have to specify `R`
type Dig<S, R> = (s: S, fn: (s: S) => R) => R;

// Generic type 'Dig' requires 2 type argument(s).
const d: Dig<string> = (s, fn) => fn(s); 

那么我怎样才能写一个Dig<S>推断传递的返回类型的类型构造函数fn没有我指定的参数R?


从 TS3.4 开始,不支持部分类型参数推断 https://github.com/Microsoft/TypeScript/issues/26242,所以你不能轻易让编译器让你指定S但推断R。但从你的例子来看,你似乎不想这样做infer R作为一些具体类型,但允许它保持通用,以便返回类型fn可以是任何它想要的,当你call d().

所以看起来你真的想要这种类型:

type Dig<S> = <R>(s: S, fn: (s: S) => R) => R;

这是一种“双重通用”类型,从某种意义上说,一旦您指定S你仍然有一个依赖于的通用函数R。这应该适用于您给出的示例:

const d: Dig<string> = (s, fn) => fn(s);

const num = d("hey", (x) => x.length); // num is inferred as number
const bool = d("you", (x) => x.indexOf("z") >= 0); // bool inferred as boolean

好的,希望有帮助。祝你好运!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

TypeScript 在类型构造函数中推断回调返回类型 的相关文章

随机推荐