2

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);
  }
}
Community
  • 1
  • 1
Luca Marangon
  • 762
  • 1
  • 8
  • 13

2 Answers2

5

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?

rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
3

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);
}
Daniel W Strimpel
  • 8,190
  • 2
  • 28
  • 38