1

I am doing the following object access. But TS complains that it may be undefined even when I check for it.

      if (metrics[key0]) {
        if (metrics[key0][key1]) {

          […]metrics[key0][key1]]);
        }
      }

=> Error TS2532 in line 2 and 4. Playground example: Click Me

When I change it to metrics[key0]?.[key1] the error is gone. But why do I need that? In the if it cannot be null or undefined?

Edit: Please do not again mark this as duplicate of this. In that topic there is no check for null or undefined.

  • Your playground contains a lot of infos. You should add some of it in the question to complete it. However, the actual type of key1 is never (it doesn't answer the question, but it shouldn't be never, should it?) – Ilario Pierbattista Jan 30 '21 at 22:39
  • This is a known behavior which happens when you are checking a variable property of an object, like `metrics[key0]`. If you save `metrics[key0]` to a variable and check that variable then you won't have the error. – Linda Paiste Jan 31 '21 at 04:09
  • @IlarioPierbattista you are right there is a small error. Type of key1 is not correct. – PeterPetersson Jan 31 '21 at 12:12
  • @LindaPaiste Thank U! – PeterPetersson Jan 31 '21 at 12:12

0 Answers0