Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript : question mark on array

Tags:

typescript

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.

like image 420
Stef1611 Avatar asked Oct 27 '22 01:10

Stef1611


1 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.

like image 131
jack Avatar answered Jan 02 '23 19:01

jack