Reputation: 39260
I can't get this to work, not sure how to explain the type to typescript for the following code:
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. The error is Property 'length' does not exist on type 'T'.
Upvotes: 1
Views: 358
Reputation: 1074178
There are two things:
CompareFn
isn't generic, the <T>
isn't quite in the right place.
Any specific CompareFn
will need to specify the generic type constraint such that the generic type has any properties that it uses.
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
. Interface and class names start with an initial uppercase character (again, by convention).
Upvotes: 1