Suppose I have two objects and I want to compare and assign specific fields between them:
const left = { a: 1, ignored: 5, something: 7 };
const right = { a: 2, ignored: 6, else: 8, id: 18 };
If I call leftToRight(left, right, ['a'])
, then the updated right
object should be:
{ a: 1, ignored: 6, id: 18 }
After this, I also need to call another function using the id
from right
.
This is my current implementation:
leftToRight(left, right, keys) {
let changed = false;
for (const key of keys) {
if (!Object.is(left[key], right[key])) {
right[key] = left[key];
changed = true;
}
}
doSomething(right.id)
return changed
}
I am facing difficulties in defining the appropriate type for this function :-(
Initially, I tried with:
leftToRight<T>(left: T, right: T, keys: Array<keyof T>): boolean
which resulted in an error "Property 'id' does not exist on type 'T'" as I couldn't find a way to check it ('id' in right
)
In my second attempt:
leftToRight<T>(left: T, right: T & {id: number}, keys: Array<keyof T>): boolean
I got the error "Type 'T' is not assignable to type '{ id: number; }' for right[key] = left[key]
For the third try:
leftToRight<T, U extends {id: number}>(left: T, right: U, keys: Array<keyof T & keyof U>): boolean
but again faced an error for the assignment right[key] = left[key]
due to the unrelated types T and U.