代码之家  ›  专栏  ›  技术社区  ›  HMR

无法用typescript定义泛型比较函数的类型

  •  1
  • HMR  · 技术社区  · 6 年前

    我无法使此工作,无法确定如何将以下代码的类型解释为typescript:

    interface hasLength {
      length: number;
    }
    type CompareFn = <T> (a: T, b: T) => boolean
    const compare = (compareFn: CompareFn, a: hasLength, b: hasLength) => 
      compareFn(a, b)
    const compareFn: CompareFn = (a, b) => a.length === b.length//error here
    const otherCompare: CompareFn = (a, b) => a === b
    console.log(compare(compareFn, [1], [2]))
    console.log(compare(compareFn, 'a', 'b'))
    console.log(compare(otherCompare, [1], [2]))
    

    compare函数获取同一类型或接口的两个参数,并用于函数比较。错误是 Property 'length' does not exist on type 'T'.

    1 回复  |  直到 6 年前
        1
  •  1
  •   T.J. Crowder    6 年前

    有两件事:

    1. CompareFn 不是普通的 <T>

    2. 任何特定的 比较

    下面是一个更正的版本,其中有注释,指出了更改/添加:

    interface hasLength {
      length: number;
    }
    
    type CompareFn<T> = (a: T, b: T) => boolean
    //            ^^^
    
    const compare = (compareFn: CompareFn<hasLength>, a: hasLength, b: hasLength) => 
    //                                   ^^^^^^^^^^^
      compareFn(a, b)
    const compareFn: CompareFn<hasLength> = (a, b) => a.length === b.length
    //                        ^^^^^^^^^^^
    const otherCompare: CompareFn<any> = (a, b) => a === b
    //                           ^^^^^
    console.log(compare(compareFn, [1], [2]))
    console.log(compare(compareFn, 'a', 'b'))
    console.log(compare(otherCompare, [1], [2]))
    

    On the playground


    旁注:按照压倒性的惯例, hasLength 应该是 HasLength . 接口和类名以大写字母开头(同样,按惯例)。

    推荐文章