Home > other >  What is the use of "?" in typescript when used after a variable
What is the use of "?" in typescript when used after a variable

Time:10-18

what is "?" in "instances?.map" doing here. I thought it was checking for instances to be non-null before executing map on it. If it is what might be the reason for this error? enter image description here

CodePudding user response:

The error does not say that instances is null, it says that it does not have a .map function.

You should check where it is declared and what it contains. It looks like an object, you cannot use .map on an object like that but it has to be an array.

CodePudding user response:

Your understanding of .? is correct.

(Its called "optional chaining". With x.y the dot is called a chaining operator. With x?.y the questionmark and dot are called an optinal chaining operator)

The reason for the error is unrelated to the optional chaining. you would've got the same error if you used normal chaining. The error is likely that "instances" is not actually a normal Array so it doesn't have the map function. It might be some kind of "Array-like object".

For example some browser api methods like document.querySelectorAll return a NodeList which lacks a map function. And you need to convert it to an Array using something like Array.from

  • Related