1

I'm using optional chaining on an object which in turn gives this error after compiling the code

For example

const someObj = {pet_animals: {'dog', 'cat'}};
const duplicate = someObj?.wild_animals;

tsconfig file

enter image description here

Error message

enter image description here

ruth
  • 29,535
  • 4
  • 30
  • 57
Prime
  • 11
  • 4
  • 1
    `{pet_animals: {'dog', 'cat'}}` is not valid code. I suspect the error comes from it, rather than the optional chaining. – VLAZ May 11 '21 at 06:41
  • Also `someObj?.wild_animals;` would likely fail to compile in TS as there is no `wild_animals` property on the object. – VLAZ May 11 '21 at 06:42
  • just so that it doesn't fail we're using optional-chaining right? – Prime May 11 '21 at 08:08
  • TBH, I don't see how it would fail - the object is definitely defined on the first line, so using optional chaining on the second line only protects if the object is `null` or `undefined`...which is never going to be the case. – VLAZ May 11 '21 at 08:09
  • well, the error message is not in regards whether wild_animals exists or not.. i'm not able to use optinal chaining in the working project while if i create new temporary project and use same data it works fine without any compilation error – Prime May 11 '21 at 08:14
  • Again: `{pet_animals: {'dog', 'cat'}}` is not valid code. – VLAZ May 11 '21 at 08:15

1 Answers1

1

optional chaining was introduced in ES2020 freeCodecamp.org. If you are your using js version before ES2020, you will get that error.

That might be the reason why you couldn't use optional chaining,

solution:

duplicate = someObj.wild_animals ? someObj.wild_animals : undefined 
Vinay Somawat
  • 639
  • 14
  • 23