Skip to content
Advertisement

Object is possibly ‘null’ .ts

I have the following function:

document.getElementById('clear').onclick = function () {
    console.log('ParticleWave will clear', pw)
    pw.clear()
}

I getting this error how I can solve this

Advertisement

Answer

The error you are getting is a TypeScript error.
What it’s telling you is that you can’t know for a fact that the element you are trying to grab actually exists.
Thus letting you know of a potential bug ahead of time.

What we can do in these cases is to employ some assertions to let TS know that we are handling it either way.
This is done by treating the case where the value will, in fact, be null.

Example:

const elClear = document.getElementById('clear')
if (elClear !== null) {
   elClear.onclick = function () {
       console.log('Hi mom!')
   }
}

Or return early instead:

const elClear = document.getElementById('clear')
if (elClear === null) {
   return
}
elClear.onclick = function () {
   console.log('Hi mom!')
}

Or use TS’ “non-null assertion operator”:

document.getElementById('clear')!.onclick = function () {
    console.log('Hi mom!')
}

Note that the last approach essentially disables TS for this specific check, as you are “telling it” that you know better and that the value is definitely not null.

Since this is unsafe and defeats the point of TS to begin with, the above methods are more advised.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement