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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With