代码之家  ›  专栏  ›  技术社区  ›  J. Hesters

如何键入curried“map”?

  •  0
  • J. Hesters  · 技术社区  · 6 年前

    我想打咖喱 map

    const double = n => n * 2;
    const map = f => arr => arr.map(f);
    const doubleArr = map(double);
    
    console.log(doubleArr([1, 2, 3]));
    // ↳ [2, 4, 6]
    

    理想情况下,TypeScript应该能够推断 double 地图 , doubleArray 接受一个数字数组并返回一个数字数组。

    const double = (n: number) => n * 2;
    const map = (f: Function) => (arr: Array<any>) => arr.map(f);
    

    但是,TypeScript抱怨 f 地图 :

    Argument of type 'Function' is not assignable to parameter of type '(value: any, index: number, array: any[]) => unknown'.
      Type 'Function' provides no match for the signature '(value: any, index: number, array: any[]): unknown'.
    

    如何在TypeScript中键入此函数?

    3 回复  |  直到 6 年前
        1
  •  1
  •   ford04    6 年前

    您可以使用以下声明:

    const double = (n: number) => n * 2;
    const map = <A, R>(f: (arg: A) => R) => (arr: A[]) => arr.map(f);
    const doubleArr = map(double); // (arr: number[]) => number[]
    
    console.log(doubleArr([1, 2, 3]));
    // ↳ [2, 4, 6]
    

    Playground sample


    说明: A R generic type parameters map(double) 返回带有签名的函数 (arr: number[]) => number[] ,因为TS能够 infer double 打字,那个 两者只能是 number 在这里。

        2
  •  2
  •   alex2007v    6 年前

    您可以声明一个接口,然后传递它而不是 Function

    interface ArrFunction<T> {
        (n: T): T
    }
    
    const double = (n: number) => n * 2;
    const map = (f: ArrFunction<any>) => (arr: Array<any>) => arr.map(f);
    
        3
  •  0
  •   Kamil Augustyniak    6 年前

    可以创建函数 map 使用两个参数:array和function,以及何时要使用此函数,您应该将一个项目从array赋给此函数。

    const double = (n: number) => n * 2;
    const map = (arr: Array<any>, f: Function) => arr.map((item: any) => f(item));
    map([1, 2, 3], double)