[英]Unable to define type for generic compare function with typescript
I can't get this to work, not sure how to explain the type to typescript for the following code:我无法让它工作,不知道如何向 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]))
The compare function gets 2 parameters of the same type or interface and is used in the function compare.比较 function 得到 2 个相同类型或接口的参数,用于 function 比较。 The error is
Property 'length' does not exist on type 'T'.
错误是
Property 'length' does not exist on type 'T'.
There are two things:有两件事:
CompareFn
isn't generic, the <T>
isn't quite in the right place. CompareFn
不是通用的, <T>
不是在正确的位置。
Any specific CompareFn
will need to specify the generic type constraint such that the generic type has any properties that it uses.任何特定的
CompareFn
都需要指定泛型类型约束,以便泛型类型具有它使用的任何属性。
Here's a corrected version with comments calling out the changes/additions:这是一个更正的版本,其中的注释指出了更改/添加:
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]))
Side note: By overwhelming convention, hasLength
should be HasLength
.旁注:按照压倒性的约定,
hasLength
应该是HasLength
。 Interface and class names start with an initial uppercase character (again, by convention).接口和 class 名称以初始大写字符开头(同样,按照惯例)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.