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.
Answer from jack on Stack OverflowI 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();
}
I’m calling a rest api using react query and it’s returning me an array of objects. I have already defined the type for that object and i’m trying to transform that response array into something else using .map or .reduce.
I have the condition for isLoading or isIdle present. So i’m assuming that after that code block, the data would be present. Is my assumption flawed?
I’m using a ternary in my return jsx function and there’s no error on my end so far. So is the question mark bad?
To clarify I am referring to the first question mark, array?.length. I saw this somewhere and can't recall what it does.
const array = [1,2,3] array?.length > 0 ? 'Array contains elements' : 'No elements within array';