Typescript "TS2532 error: possibly an undefined object" even after undefined checking

I am trying to use the parameter --stricton tsc, but I came across the following "strange" case, which I don’t seem to understand.

If I write:

function testStrict(input: {query?: {[prop: string]: string}}) {
  if (input.query) {
    Object.keys(input.query).forEach(key => {
      input.query[key];
    })
  }
  return input;
}

the compiler complains:

test.ts (5,9): error TS2532: the object is possibly "undefined".

(line violation input.query[key];)

What I do not understand, I already checked for undefined with if protection in the first line of the function if (input.query), so why the compiler believes that it can be undefined

I fixed this by adding another identical protector before accessing the object, for example:

function testStrict(input: {query?: {[prop: string]: string}}) {
  if (input.query) {
    Object.keys(input.query).forEach(key => {
      if (input.query) {
        input.query[key];
      }
    })
  }
  return input;
}

but I don’t understand why another identical line is needed.

+13
source share
1

input.query , forEach. , , , .

, , undefined :

function testStrict(input: { query?: { [prop: string]: string } }) {
    if (input.query) {
        const query = input.query;
        Object.keys(input.query).forEach(key => {
            query[key];
        })
    }
    return input;
}
+13

Source: https://habr.com/ru/post/1695650/


All Articles