![](/img/trans.png)
[英]How to define a generic anonymous function type in TypeScript?
[英]Unable to define type for generic compare function with typescript
我无法让它工作,不知道如何向 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]))
比较 function 得到 2 个相同类型或接口的参数,用于 function 比较。 错误是Property 'length' does not exist on type 'T'.
有两件事:
CompareFn
不是通用的, <T>
不是在正确的位置。
任何特定的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]))
旁注:按照压倒性的约定, hasLength
应该是HasLength
。 接口和 class 名称以初始大写字符开头(同样,按照惯例)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.