input!.addEventListener('keyup', (event) => {
console.log(event.target.value);
});
TS compiler claims that event
might be null
. How could this be? By definition, this is a callback function that will be invoked whenever there is a keyup
event.
I understand that this can be easily resolved with: (event.target as HTMLSelectElement).value
. I'm not asking about a solution for this. I am curious as to what TS is.
Why/how can event
be null
inside a callback function for that event?
The EventTarget
type does not inherit from HTMLElement
by default because html elements are not the only things that can be event targets.
Based on this
Element, Document, and Window are the most common event targets, but other objects can be event targets, too. For example XMLHttpRequest, AudioNode, AudioContext, and others.
So if your input
is HTMLElement
the EventTarget
must not be null and you already have solution ((event.target as HTMLSelectElement).value
).
But as I said EventTarget
is a more abstract interface than Element
and in typescript it is in EventTarget | null
type.
Event.target: EventTarget | null
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With