0

I'm using Optional chaining operator which should solve this error, but in my loop allLinks.length i'm getting Object is possibly 'undefined'.ts(2532) (my code works fine, just want to get rid of this error.) i can fix it like this but its not right way : const allLinks : any = props.Data?.nodes;

any suggestion is appreciated.

what am I doing wrong here ?

  const allLinks = props.Data?.nodes;
      for (let i = 0; i < allLinks?.length; i++) {
        if (
          allLinks?.[i].source == currentCam.id 
        ) {
          dispatch(linkById(allLinks?.[i].id));
        }
      }
Debug Diva
  • 26,058
  • 13
  • 70
  • 123
walee
  • 575
  • 4
  • 16
  • Does this answer your question? [Object is possibly 'undefined' Error on Optional Chaining Typescript](/q/66017941/90527) – outis Oct 13 '22 at 15:22
  • By using optional chaining you're telling TS that the "Object is possibly 'undefined'" which is the warning it's giving you. [A possible solution](https://stackoverflow.com/questions/66017941/object-is-possibly-undefined-error-on-optional-chaining-typescript). – Andy Oct 13 '22 at 15:24
  • @Andy even without optional chaining its giving same warning – walee Oct 13 '22 at 15:25

1 Answers1

2

You are doing it in correct way, Just a suggestion - You can use Nullish coalescing operator (??) along with Optional chaining (?.) operator.

const allLinks = props.Data?.nodes ?? []

It will provide a fallback value when dealing with null or undefined values.

Debug Diva
  • 26,058
  • 13
  • 70
  • 123
  • @walee Done. Kindly do accept this answer if it helps you. So that it will be helpful for other fellow developers as well facing same problem. – Debug Diva Oct 20 '22 at 14:30