[英]Typescript generic interface with union type
我想使用這樣的通用聯合類型的接口:
interface IOperator {
<U>(a: U[], b: U[] | U): boolean
}
export const intersects: IOperator = (a, b) => a.some((el) => b.includes(el))
export const includes: IOperator = (a, b) => a.includes(b)
但是,TS 給了我關於其中一種聯合類型的錯誤:
Property 'includes' does not exist on type 'U | U[]'.
Property 'includes' does not exist on type 'U'.
我如何在這里正確地進行類型轉換?
我試過了:
export const intersects: IOperator = (a, b) => a.some((el) => (b as U[]).includes(el))
但是,這給了我一個錯誤:
Cannot find name 'U'.
那么如何處理泛型聯合類型呢?
我知道對於intersects
方法,輸入b
的類型應僅為 arrays,對於includes
方法,輸入b
的類型絕不應為 arrays。 接口的想法是不要重復自己,因為我有很多方法,其中一些要求b
是一個數組,而另一些則不是一個數組。 我會盡量避免創建兩個單獨的接口。
謝謝!
我認為:
export const intersects: IOperator = (a, b) => a.some((el) => Array.isArray(b)&&b.includes(el))
應該管用。 否則,b 可能不是 U 類型的數組,因此包含不可用。
在這里使用強制轉換的問題是,如果B
的值與您的強制轉換不匹配,您將遇到運行時錯誤。 話雖如此,您的用例可能是有效的,我們只是沒有可用的上下文來查看它。 否則,您可能需要按照您帖子的某些評論的建議進行運行時檢查。
此解決方案使用function
授予您對U
的訪問權限,然后將 function 分配給const
以便您可以鍵入檢查您的 function 是否與您的簽名接口匹配。
interface IOperator {
<U>(a: U[], b: U[] | U): boolean
}
function _intersects <U>(a: U[], b: U[] | U): boolean {
return a.some((el) => (b as U[]).includes(el));
}
export const intersects: IOperator = _intersects;
function _includes <U>(a: U[], b: U[] | U): boolean {
return a.includes(b as U);
}
export const includes: IOperator = _includes;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.