2

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

6
  • 1
    {pet_animals: {'dog', 'cat'}} is not valid code. I suspect the error comes from it, rather than the optional chaining. Commented May 11, 2021 at 6:41
  • Also someObj?.wild_animals; would likely fail to compile in TS as there is no wild_animals property on the object. Commented May 11, 2021 at 6:42
  • just so that it doesn't fail we're using optional-chaining right? Commented May 11, 2021 at 8: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. Commented May 11, 2021 at 8: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 Commented May 11, 2021 at 8:14

1 Answer 1

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 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.