Search code examples
angulartypescriptangular13

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?


Solution

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