Typescript : question mark on array

Viewed 8287

This is the skeleton of my code :

var myArray: (Array<any> | null);
if (cnd) {
  myArray = [];
  myArray?.push(elt); // Question 1
  myArray[0].key = value; //Question 2
} else {
  myArray = null;
}

Question 1 : Why ? is needed ? myArray has been assigned to an empty array.

Question 2 : What is the syntax to avoid error : Object is possibly null.

Thanks for answer.

2 Answers

I think the answer is that humans are still smarter than typecheckers. I know that's not satisfying, but it's true. The typechecker typically uses just conditional statements to determine whether something can be null. But this code example feels a little contrived. I would probably restructure the code like this:

var myArray: (Array<any> | null);
if (cnd) {
  elt.key = value;
  myArray = [elt];
} else {
  myArray = null;
}

This removes those two oddities.

For question 1, you can refer to this link

For question 2, just perform a check against null like this before accessing your object

if (obj !== null) {
    obj.doSomeThing();
}

or just simply like the following if your object can be null or undefined. null and undefined are what are called falsy value, so when they are used in a boolean context, they are automatically coerced to false

if (obj) {
    obj.doSomeThing();
}
Related