Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could an event received in a callback for addEventListener be null?

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?

like image 334
CodeFinity Avatar asked Sep 11 '25 18:09

CodeFinity


1 Answers

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
like image 94
Alireza Ahmadi Avatar answered Sep 16 '25 08:09

Alireza Ahmadi