5

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.

1

2 Answers 2

2

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.

2
  • 1
    I like you remark " humans are still smarter than typecheckers"
    – Stef1611
    Feb 28, 2020 at 19:35
  • I am sorry. I accept the other answer because of my full code but I am sure your answer will help me in the future. Pity, that is not possible to accept 2 answers.
    – Stef1611
    Feb 28, 2020 at 19:41
0

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();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.