Reputation: 534
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?
Upvotes: 13
Views: 8513
Reputation: 1827
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!
});
Upvotes: 26
Reputation: 30939
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
.
Upvotes: 1