繁体   English   中英

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

[英]TypeScript infer the callback return type in type constructor

我想为一个接收类型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); 

那么,如何在不指定R情况下编写Dig<S>类型的构造函数来推断所传递的fn参数的返回类型呢?

从TS3.4开始,不支持部分类型参数推断 ,因此,您不能轻易让编译器指定S但可以推断R 但是从您的示例来看,您似乎不希望将R 推断为某种具体类型,而是让其保持通用性,以便fn的返回类型可以是您调用 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

好的,希望对您有所帮助。 祝好运!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM