【问题标题】:flow input type - why we need to type double array like type[][]?流输入类型 - 为什么我们需要输入像 type[][] 这样的双数组?
【发布时间】:2023-02-17 04:17:33
【问题描述】:

我正在使用函数式编程库,并且有一个类似管道的函数叫做流。它的用法看起来像这样

flow(
  map(item => item.toString())
)([1, 2, 3])

Flow 是通用的,因此在这种情况下它需要 2 个类型参数。第一个用于输入 ([1, 2, 3]),第二个用于整个流程返回的内容(在本例中为 ['1', '2', '3']。知道我' m 输入流程

flow<number[], string[]>...

但后来我得到错误,只有当我输入它时才会消失

flow<number[][], string[]>...

流的类型定义如下所示

export declare function flow<A extends ReadonlyArray<unknown>, B>(ab: (...a: A) => B): (...a: A) => B

请告诉我为什么在这种情况下我需要做双阵列。

【问题讨论】:

  • 好吧,它与 Typescript 和 ts 打字的工作方式密切相关。 fp-ts 是用 Typescript 编写的,使用 Typescript 类型,库只是一个插件。根据附加的代码,我想知道为什么 Typescript 在这种情况下需要 double [][] 来键入。
  • 啊,我读得有点快。感谢您的澄清。以为我们在谈论流类型。

标签: javascript typescript fp-ts


【解决方案1】:

flow 函数旨在处理多个参数。通用类型 A 将这些参数的类型表示为元组.

虽然输入 Anumber[][] 似乎解决了您的问题,但您实际上应该将其输入为 [number[]],代表单身的number[] 类型的参数。

flow<[number[]], string[]>(
  map(item => item.toString())
)([1, 2, 3])

使用多个不同的参数键入 flow 将如下所示:

const someOperator = (arg_0: number[], arg_1: string) => [arg_1]

flow<[number[], string], string[]>(
    someOperator
)([1, 2, 3], "")

【讨论】:

    猜你喜欢
    • 2020-10-05
    • 1970-01-01
    • 2021-05-01
    • 2013-10-11
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    相关资源
    最近更新 更多