Why Typescript type guard not worked while use object from object key? (2345)

Viewed 18

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));

https://www.typescriptlang.org/play?#code/C4TwDgpgBA8gRgKygXigbygbQG4EMA2AXFAM7ABOAlgHYDmAusWVXVAD6yJQC+A3ALAAoIQGMA9tTJRxAV2rAA0hBAkUUABRjEARmLwEAGihaEAJj2IAlMWoyAtnAjkUAPnRCon6RKmz5a-QgRYAA6CHkqCBJNHUsQ8ggAExkRCHV1MATsI0wAa2UjPHwZCHpLV3dBL2qoSgAzDVBIMQaikpRkVAByEyDgLvK0DxrqhOAZcmooJogW40RTAH4QvOV6KABCTqgu5hpaLuGR6sWoTIhsKABqbzlFZWi2iCMTJZX8kDKj489ic8ubtoBFVjtxvqMIONJvMzMtMOoPpZ1qd-lA-llrlAgd9uEYAAyWYHfMYTKZ+YDAvhCUQ+YDTKLAbRqIYg3DELraLoGYZwdmmLnDETsgDMApBiWILOqEHZABZOdyQZ46nL+YrPLjhrRJd8ABbshXDTWCMHCQTiSR04AM0zM4ZsnaGkG8nZq4YSyrSuVOjVCU00yRifAQEL4MS0dTkpQqdTWsjaIxx4CmSyEoA

0 Answers
Related