TS shows an error if you use the obj2?.[key] key, but if you assign this key to a variable above and use it, type guard works correctly and the error disappears. Why is this happening?
type Obj = { [val: string]: string | Obj };
const countKeys = (obj1: Obj, obj2: Obj): number => {
const count = Object.entries(obj1).reduce((prev, [key, value]) => {
if (typeof value === 'object') {
return typeof obj2?.[key] !== 'string'
? prev + countKeys(value, obj2?.[key]) // <----------------- Argument of type 'string | Obj' is not assignable to parameter of type 'Obj'
: prev + 1;
}
return obj2?.[(key)] ? prev : prev + 1;
}, 0);
return count;
};
const test1 = {
a: '1',
b: '2',
c: '3',
d: {
e: '41',
f: '42',
},
g: {
h: '1',
},
}
const test2 = {
a: '1',
b: '2',
d: {
e: '41',
}
}
console.log(countKeys(test1, test2));