I am trying to compare if an item exists in another array by checking a common property value. For the below code it is throwing the below error:
TS2367: This condition will always return 'false' since the types 'U[K]' and 'T[K]' have no overlap.
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;
}
Below is the TS playground link for the above code problem: