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

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.