【问题标题】:How do I assign the right type signature to this curried function in typescript?如何在打字稿中为这个咖喱函数分配正确的类型签名?
【发布时间】:2019-04-14 06:52:20
【问题描述】:

我是打字稿和泛型的新手,并且正在使用 Maybe monad。我使用 Ramda 创建了这个小实用函数:

const fromEmpty = R.ifElse(hasLength, Just, Maybe.zero);

我可以从中推断出的最接近的签名是:

type EmptyFunc<T> = (val: T[]) => Maybe<T[]>;

这是一个函数,接收一个数组并返回一个返回该数组的 Maybe 的函数。

我试过了

const fromEmpty(<U extends EmptyFunc<U>) = R.ifElse(hasLength, Just, Maybe.zero);

但这不起作用。它返回error TS1005: ',' expected.

在打字稿中使用柯里化函数的正确方法是什么?

【问题讨论】:

    标签: typescript functional-programming currying ramda.js


    【解决方案1】:

    声明

    type EmptyFunc<T> = (val: T[]) => Maybe<T[]>;
    

    声明了一系列不同的函数类型EmptyFunc&lt;number&gt;EmptyFunc&lt;string&gt;等,每一个都只适用于指定的类型T。你可能是说

    type EmptyFunc = <T>(val: T[]) => Maybe<T[]>;
    

    它声明了适用于所有类型T 的单个泛型函数的类型EmptyFunc。然后将此类型应用于fromEmpty,只需编写:

    const fromEmpty: EmptyFunc = R.ifElse(hasLength, Just, Maybe.zero);
    

    (由于您没有给出hasLengthJustMaybe 的定义,我无法自己对此进行测试。)如果这不是您要问的,请澄清问题。

    【讨论】:

      猜你喜欢
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-18
      • 1970-01-01
      • 2013-02-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多