I have two objects with similar properties. I want to compare the values of each property in both objects and find the differences.
The following code is functional but generates TypeScript errors:
export type Item = {
name?: string;
age?: number;
location?: {
x: number,
y: number
}
};
const item1: Item = { name: "Jim", age: 32, location: {x: 1, y: 2} };
const item2: Item = { name: "Jim" };
const itemDiff: Item = {};
Object.entries(item1).forEach(([key, value]) => {
if (item1[key] !== item2[key]) {
itemDiff[key] = value;
}
});
An 'any' type error occurs because a 'string' expression cannot index type 'Item'. No signature using 'string' found in type 'Item'.ts(7053)
To reduce the errors, I utilized the ts-extras
library:
objectEntries(item1).forEach(([key, value]) => {
if (item1[key] !== item2[key]) {
itemDiff[key] = value;
}
});
However, I still encounter an error at itemDiff[key] = value;
:
(parameter) key: keyof Item Type 'string | number | { x: number; y: number; } | undefined' is not assignable to type 'undefined'. Type 'string' is not assignable to type 'undefined'.ts(2322)