Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property innerWidth does not exist on type EventTarget

When I run a code:

public onResize(event: Event) {
    console.log(event.target.innerWidth);

    //--solution--
    //var w = event.target as Window;
    //console.log(w.innerWidth);
  }

I receive an error:

Property innerWidth does not exist on type EventTarget

I would like to avoid extending types in TypeScript (as it is described here Property 'value' does not exist on type 'EventTarget' ), so I cast event.target to Window class. I'm not sure if I cast to proper class. Which class should I cast to? How to find out a proper class which should be cast to?

like image 491
ael Avatar asked Aug 21 '18 19:08

ael


People also ask

How do you solve Property value does not exist on type EventTarget?

js error "Property 'value' does not exist on type EventTarget" occurs when the type of the event parameter is incorrect. To solve the error, type the event as React. ChangeEvent<HTMLInputElement> . You can then access the value as event.

Does not exist on type event target?

The error "Property 'value' does not exist on type 'EventTarget'" occurs when we try to access the value property on an element that has a type of EventTarget . To solve the error, use a type assertion to type the element correctly before accessing the property. This is the index.

What is the type of event target?

The target event property returns the element that triggered the event. The target property gets the element on which the event originally occurred, opposed to the currentTarget property, which always refers to the element whose event listener triggered the event.


2 Answers

  1. A resize event uses the UIEvent Interface.

    https://developer.mozilla.org/en-US/docs/Web/API/Window/resize_event

  2. A UIEvent has a target property which, unfortunately, has no "innerWidth" property. So, instead, we assert the target of the event as Window

i.e.

window.addEventListener('resize', (event: UIEvent) => {
  const w = event.target as Window; 
  console.log(w.innerWidth) // works!
});
like image 97
Brandon Avatar answered Oct 13 '22 04:10

Brandon


If you know what element you registered the event listener on, then you could cast event.target to that element type. I don't think there's any more to say than that. Alternatively, you can directly reference the element you registered the listener on (in this case just the global window) rather than using event.target.

like image 45
Matt McCutchen Avatar answered Oct 13 '22 04:10

Matt McCutchen