Reputation: 792
So I have a function that requires a certain non nullable type. Before calling the function I check if the input parameter is not null but, apparently, typescript can't understand that and complains saying:
Argument of type 'HermiteOctreeNode | undefined' is not assignable to parameter of type 'HermiteOctreeNode'.
Type 'undefined' is not assignable to type 'HermiteOctreeNode'.
if (node.nodeType !== NODE_TYPE_LEAF && node.nodeType !== NODE_TYPE_PSEUDO) {
for (let i = 0; i < node.children.length; i++) {
if (node.children[i] != null) {
rebuildOctreeNode(node, /* node.children[i] HERE /*, i);
}
}
Upvotes: 2
Views: 1163
Reputation: 8470
As another solution, you can store the array value in a variable and it will resolve your issues:
const child = node.children[i];
if (child != null) {
rebuildOctreeNode(node, child, i);
}
Upvotes: 3
Reputation: 46208
If you are absolutely certain that the operator is not null, you can use the non-null assertion operator (!
):
if (node.children[i] !== null) {
rebuildOctreeNode(node, node.children[i]!, i);
}
There's more information about this operator on this question: In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?
Upvotes: 5