Can it be that TypeScript DOM types for events and React Event types don't go well with another?
Look at this code:
useEffect(() => {
const onScroll = (event: React.ChangeEvent<Body>) => {
console.log("event", event.target);
};
window.addEventListener("scroll", onScroll);
return () => window.removeEventListener("scroll", onScroll);
}, []);
It throws
No overload matches this call.
Overload 1 of 2, '(type: "scroll", listener: (this: Window, ev: Event) => any, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
Argument of type '(event: ChangeEvent<Body>) => void' is not assignable to parameter of type '(this: Window, ev: Event) => any'.
Types of parameters 'event' and 'ev' are incompatible.
Type 'Event' is not assignable to type 'ChangeEvent<Body>'.
Than I tried the following. This compiles correctly.
useEffect(() => {
const onScroll = (event: Event) => { // <--- changed event type here
console.log("event", event.target);
};
window.addEventListener("scroll", onScroll);
return () => window.removeEventListener("scroll", onScroll);
}, []);
event.target
can not be access without compile errors, though. I checked the following function call (it is working in the browser if I ts-ignore the error):
useEffect(() => {
const onScroll = (event: Event) => {
console.log(
"event",
event?.target?.activeElement.getBoundingClientRect() // <--- this function call is actually working (ts-ignored it), even if TypeScript throws an error
);
};
window.addEventListener("scroll", onScroll);
return () => window.removeEventListener("scroll", onScroll);
}, []);
throws
TypeScript error in /home/sirhennihau/Workspace/giphy-search/src/Components/grid.tsx(27,24):
Property 'activeElement' does not exist on type 'EventTarget'. TS2339
25 | console.log(
26 | "event",
> 27 | event?.target?.activeElement.getBoundingClientRect()
| ^
28 | );
29 | };
30 |
My dependencies:
"@types/node": "^12.0.0",
"@types/react": "^16.9.53",
"@types/react-dom": "^17.0.0",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.1",
"typescript": "^4.0.3"
Are maybe just the typings bad or am I doing something wrong?