Home > Software design >  Object is possibly 'null'.ts(2531), Error occurs even though I am checking that in the if
Object is possibly 'null'.ts(2531), Error occurs even though I am checking that in the if

Time:04-11

if (document.getElementById(`${element.id}-element`)) {
    document.getElementById(`${element.id}-element`).onmousedown =   // *document.getElementById(`${element.id}-element`)* gives me object is possibly null error                                                              
     dragMouseDown;
  } else {
    element.onmousedown = dragMouseDown;
  }

So I tried the non-null assertion

if (document.getElementById(`${element.id}-element`)) {
    document.getElementById(`${element.id}-element`)!.onmousedown =
      dragMouseDown;
  } else {
    element.onmousedown = dragMouseDown;
  }

But this gives me Forbidden non-null assertion @typescript-eslint/no-non-null-assertion. Is there any other approach to avoid the object possibly null error?

Thanks in Advance :)

CodePudding user response:

Instead of repeating the expression, store it into a variable.

const element2 = document.getElementById(`${element.id}-element`);
if (element2) {
    element2.onmousedown = dragMouseDown;
} else {
    element.onmousedown = dragMouseDown;
}

Even better, use nullish coalescing and get rid of the if-else block.

const element2 = document.getElementById(`${element.id}-element`) ?? element;
element2.onmousedown = dragMouseDown;
  • Related