I was trying to solve this other question's problem which involves iterating through two objects of the same unknown type and adding together their number-typed properties without type assertions (if possible).
I got close (I thought I had it down to one type assertion) but I'm flummoxed by something I ran into: Why in the following can I use key
to index result
and currentValue
when getting the value of a property, but not when setting the value of a property?
const a = {x:1, y:1, z:1};
const b = {x:2, y:2, z:2};
function reduceObjects<T extends {[key: string]: any}>(currentValue: T, previousValue: T): T {
const result = Object.assign({}, previousValue) as T;
for (const key of Object.keys(result)) {
const prev = result[key];
// ^^^^^^^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− why is this okay...
const curr = currentValue[key];
if (typeof prev === "number" && typeof curr === "number") {
result[key] = prev + curr;
// ^^^^^^^^^^^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−− ...but this isn't?
// "Type 'string' cannot be used to index type 'T'.(2536)"
} else if (typeof prev === "string" && typeof curr === "string") {
result[key] = prev + curr;
// ^^^^^^^^^^^ (same error here of course)
}
}
return result;
}
const c = reduceObjects(a, b);
My question is why is the error there. I'm not really trying to fix it (though if you can fix the above — probably with a different approach entirely — I do recommend you post an answer to the other question ). I want to understand why it matters whether I'm getting or setting the property.
Titian Cernicova Dragomir pointed out that this changed between v3.3 (where it worked) and v3.5 onward (where it stopped working).