【问题标题】:TypeScript infer the callback return type in type constructorTypeScript 在类型构造函数中推断回调返回类型
【发布时间】:2019-09-03 11:01:54
【问题描述】:

我想为一个函数编写一个类型构造函数,该函数接收一个类型 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&lt;S&gt; 类型构造函数来推断传递的fn 参数的返回类型,而无需我指定R

【问题讨论】:

    标签: typescript generics type-inference


    【解决方案1】:

    从 TS3.4 开始,不支持 partial type argument inference,因此您不能轻易让编译器让您指定 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
    

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

    【讨论】:

    • 太棒了。我从 flow 中知道 doubly generic 类型,但不知道 TS 支持它。
    • doubly generic有官方文档吗?
    • 我只是使用“双重通用”这个词,因为没有更好的东西......目前找不到文档
    • 在名为Generic values 的问题中对 TypeScript 中的泛型类型进行了很好的讨论。我给出的Dig 定义是通用type(类型多态性)与通用function(值多态性)的组合。
    • 非常好。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-04
    • 2020-01-23
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    相关资源
    最近更新 更多