簡體   English   中英

無法為通用比較 function 與 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'.

有兩件事:

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

在操場上


旁注:按照壓倒性的約定, hasLength應該是HasLength 接口和 class 名稱以初始大寫字符開頭(同樣,按照慣例)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM