无法使用打字稿为通用比较功能定义类型

时间:2020-06-20 10:11:30

标签: typescript generics

我无法使用它,不确定下面的代码如何解释打字稿的类型:

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函数获得2个相同类型或接口的参数,并在函数比较中使用。错误是Property 'length' does not exist on type 'T'.

1 个答案:

答案 0 :(得分:1)

有两件事:

  1. CompareFn不是通用名称,<T>不太正确。

  2. 任何特定的CompareFn都需要指定通用类型约束,以便通用类型具有其使用的任何属性。

这是经过更正的版本,带有注释,指出了更改/添加内容:

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。接口和类名称以大写字母开头(同样,按照惯例)。