Search code examples
javascripttypescriptfp-ts

flow input type - why we need to type double array like type[][]?


I'm using functional programming library and there is pipe-like function called flow. It's usage looks like this

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

Flow is generic so it takes in this case 2 type arguments. The first one is for input ([1, 2, 3]) and the second one is for what the entire flow returns (in this case it is ['1', '2', '3']. Knowing that I'm typing the flow

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

but then I get error which disappears only when I type it like

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

The type definition for flow looks like this

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

Tell me please why I need to do double array in this case please.


Solution

  • The flow function is designed to handle more than one argument. The generic type A represents the type of these arguments as a tuple.

    While typing A as number[][] seemingly solved your problem, you are really supposed to type it as [number[]], representing a single argument which is of type number[].

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

    Typing flow with multiple different arguments would look like this:

    const someOperator = (arg_0: number[], arg_1: string) => [arg_1]
    
    flow<[number[], string], string[]>(
        someOperator
    )([1, 2, 3], "")