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?
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.
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.
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.
A resize event uses the UIEvent Interface.
https://developer.mozilla.org/en-US/docs/Web/API/Window/resize_event
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!
});
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
.
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