[英]Typescript: Compare two different Array of objects having a common key and get common objects from source array
我試圖通過檢查一個公共屬性值來比較一個項目是否存在於另一個數組中。 對於下面的代碼,它拋出以下錯誤:
TS2367:此條件將始終返回 'false',因為類型 'U[K]' 和 'T[K]' 沒有重疊。
const sourceArray = [{requestId: "1", name: "henry"},{requestId: "2", name: "bob"}]
const arrayListToCompareWith = [{requestId: "1", age: 30}, {requestId: "9", age: 40}]
const commonItems = getItemsInSourceArrayWhichArePresentInArrayToBeComparedWith(sourceArray,arrayListToCompareWith, "requestId" )
function getItemsInSourceArrayWhichArePresentInArrayToBeComparedWith<
T,
U,
K extends keyof T & keyof U,
>(
sourceArray: T[],
arrayListToCompareWith: U[],
comparisonKey: K, // "requestId"
) {
const itemsInSourceArrayWhichAreNotPresentInArrayToBeComparedWith: T[] =
sourceArray.filter((sourceArrayItem: T): boolean => {
const { [comparisonKey]: sourceArrayItemComparisonKeyValue } = sourceArrayItem; sourceArrayItemComparisonKeyValue
const itemExistsInTheArrayWeAreComparingWith: boolean =
arrayListToCompareWith.some((itemToCompareWith: U): boolean => {
const comparisonValueInItemToCompareWith = itemToCompareWith[comparisonKey]; // U[K]
const comparisonValueInSource = sourceArrayItemComparisonKeyValue; //T[K]
// TS2367: This condition will always return 'false' since the types 'U[K]' and 'T[K]' have no overlap.
const check = comparisonValueInItemToCompareWith === comparisonValueInSource;
return check;
});
return itemExistsInTheArrayWeAreComparingWith;
});
return itemsInSourceArrayWhichArePresentInArrayToBeComparedWith;
}
以下是上述代碼問題的 TS 游樂場鏈接:
問題是您沒有告訴 Typescript T
和U
之間存在任何關系,特別是您沒有說它們必須具有相同的屬性K
值類型。
實際上不需要你的第二個類型參數U
- 我們需要說的是第二個數組包含具有與T
相同值類型的鍵K
對象。 這可以更簡單地寫為Pick<T, K>
。
function filterByKey<T, K extends keyof T>(arr: T[], keysToKeep: Pick<T, K>[], key: K) {
return arr.filter(
item => keysToKeep.some(
otherItem => item[key] === otherItem[key]
)
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.