I am trying to define a function that can take two objects of different types but with the same keys:
function myFunc(left, right, keys) {
// simplified:
for (const key of keys) {
console.log(key, left[key] === right[key])
}
return { left, right }
}
const left = {a: 1, b: 2}
const right = {b: 2, c: 3}
myFunc(left, right, ["b"])
The current implementation changes the type of the returned right
, which causes issues in subsequent code after calling the function:
function myFunc<
Left,
Keys extends keyof Left
>(
left: Left,
right: Pick<Left, Keys>,
keys: Keys[],
): {
left: Left
right: Pick<Left, Keys>
} {
// ...
}
I want the returned type to remain the same:
function myFunc<
Left,
Right extends Pick<Left, Keys>,
Keys extends keyof Left & keyof Right
>(
left: Left,
right: Right,
keys: Keys[]
): {
left: Left
right: Right
} {
// ...
}
However, I am getting an error about the types Left[Keys]
and Right[Keys]
not overlapping, which I am struggling to understand.
Any suggestions or insights?