deszok
deszok

Reputation: 175

Angular 13 Cannot get rid of Object is possible null

I have some code that contains this:

var element = document.getElementById("div0");
    element.parentNode.removeChild(element); // Error points here

I keep getting:

object is possibly 'null' and tried added ! to element but it still complains.

How can I get rid of this error?

Upvotes: 1

Views: 1961

Answers (2)

David Heuschmann
David Heuschmann

Reputation: 3

This is an error thrown by typescript, because the return type of document.getElementById is HTMLElement | null. You could disable this check by setting strictNullChecks: false in your tsconfig, however this is a helpful check, since the call might actually return null if the element does not exist in the DOM. You have other options to deal with this without disabling the check.

You could check for null and handle the case:

const element = document.getElementById('div0');
if (element === null) {
  // you should handle the case in an appropriate way here
  throw new Error('Element "div0" does not exist.');
}

// after the check above, the error will not be thrown anymore
element.parentNode.removeChild(element);

You could use the ! operator to tell typescript that it should assume the value will never be null:

const element = document.getElementById('div0')!;
element.parentNode.removeChild(element);

Note that this approach will lead to a runtime error if element is null during runtime.

Or you could use the ? to only call removeChild if element is not null:

const element = document.getElementById('div0');
element?.parentNode.removeChild(element);

This will only access parentNode on element if element is not null. Otherwise the expression will evaluate to null and removeChild is not called.

Upvotes: 0

Batajus
Batajus

Reputation: 6267

As already mentioned by @Sh. Pavel it is a Typescript error.

From my point of view you have several options but I just point out two options, which I think are the best for your issue.

Option 1: Optional Chaining

By using optional chaining the code stops the execution if it runs into a null or undefined. Also, it produces cleaner and less code than adding a guard for each potentially nullable property.

const element = document.getElementById("div0");
element?.parentNode?.removeChild(element);

Option 2: Guard

By using a guard the code part can only be reached if the condition is true, so Typescript understand that the values are defined then

const element = document.getElementById("div0");
if (element && element.parentNode) {
  element.parentNode.removeChild(element);
}

Upvotes: 2

Related Questions