TypeScript推断类型构造函数中的回调返回类型 [英] TypeScript infer the callback return type in type constructor

查看:80
本文介绍了TypeScript推断类型构造函数中的回调返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to write a type constructor for a function which receives a type S and a function from S to another type then applies that function on the S and returns the result:

// 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 ?

So how can I write a Dig<S> type constructor which infers the return type of the passed fn argument without me specifying the R?

推荐答案

从TS3.4开始,不支持部分类型参数推断,因此您不容易让编译器让您指定 S 但推断 R .但是从您的示例来看,您似乎并不想像某些具体类型那样推断 R ,而是允许其保持通用性,从而使的返回类型fn 可以是您呼叫 d()时想要的任何形式.

As of TS3.4 there is no support for partial type argument inference, so you can't easily have the compiler let you specify S but infer R. But from your example, it doesn't look like you want to infer R as some concrete type, but allow it to remain generic so that the return type of fn can be whatever it wants to be when you call d().

看起来您真的想要这种类型:

So it looks like you really want this type:

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

这是一种双重通用"类型,从某种意义上说,一旦指定了 S ,您仍然可以获得依赖于 R 的通用函数.这应该适用于您给出的示例:

This is sort of a "doubly generic" type, in the sense that once you specify S you've still got a generic function dependent on R. This should work for the example you gave:

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

好的,希望能有所帮助.祝你好运!

Okay, hope that helps. Good luck!

这篇关于TypeScript推断类型构造函数中的回调返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆