简体   繁体   中英

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:

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'.

There are two things:

  1. CompareFn isn't generic, the <T> isn't quite in the right place.

  2. 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]))

On the playground


Side note: By overwhelming convention, hasLength should be HasLength . Interface and class names start with an initial uppercase character (again, by convention).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM