簡體   English   中英

如何在打字稿中正確重載具有多個參數的函數?

[英]How to overload a function with multiple parameters correctly in typescript?

我正在嘗試定義一個函數includes ,它適用於數組和字符串。

但是我無法正確輸入它。 如果我理解正確,則可以使用聯合進行重載。 所以這就是我正在嘗試的:

// Declarations
export function includes<T>(arr: T[], el: T): boolean;
export function includes(str: string, substr: string): boolean;
// Implementation
export function includes<T>(arr: T[] | string, el: T | string) {
  return arr.indexOf(el) !== -1;
}

但我收到錯誤:

'string' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype

這是有道理的,因為如果arrT類型,則el不應該是string類型,但聯合使它成為“可能性”。

那么我如何正確輸入這里的實現來說明參數可能是T[] and Tstring and string

調用arr.indexOf(el)是不安全的,其中arrT | string[] T | string[]elT | string T | string因為編譯器不確定您是否不匹配它們,如"typescript".indexOf(2)[1,2,3].indexOf("rip") arrel的類型應該相關這一事實在 TypeScript 中很難表達。 在沒有相關記錄類型的情況下(參見 microsoft/TypeScript#30581) ],在實現中使用any或其他變通方法等不太安全的事情是合理的,因為重載調用簽名可以防止調用者看到任何此類不健全的情況你的功能。

但是,在您的情況下,我傾向於使用以下實現簽名:

export function includes<T>(arr: { indexOf(x: T): number }, el: T) {
    return arr.indexOf(el) !== -1;
}

在這里,我們只關心arr有一個indexOf()方法,它接受某種類型T的值並返回一個number ,而el是一個T 這使得arr.indexOf(el)編譯都不會出錯,並且它與兩個重載調用簽名兼容。 事實上,您甚至可能想要放棄重載而只使用上面的定義,除非您有某種理由將 contains includes()限制為string - 或 - Array<T>輸入。 讓我們確保它的行為:

includes("typescript", "rip"); // okay
includes([1, 2, 3], 2); // okay

includes("typescript", 2); // error
includes([1, 2, 3], "rip"); // error

在我看來很好。 希望有所幫助; 祝你好運!

代碼鏈接

暫無
暫無

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

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