The situation is somewhat like:
const searchKeyPressHandler = (appDispatch: any, e: any) => {
if (e.keyCode === 27) {
appDispatch({ type: "closeSearch" })
}
}
document.addEventListener("keyup", searchKeyPressHandler); // <-- error on searchKeyPressHandler
return () => document.removeEventListener("keyup", searchKeyPressHandler); // <-- error on searchKeyPressHandler
searchKeyPressHandler
return error using typescript and I don't know how I can avoid it.
document.addEventListener("keyup", function (e) { searchKeyPressHandler(appDispatch, e) });
could be a solution for addEventListener
but it is not useful for removeEventListener
because the event will be never removed with
return () => document.removeEventListener("keyup", function (e) { searchKeyPressHandler(appDispatch, e) });
.
Just wrap the actual event handler in an anonymous function and that function can then call your function with its arguments. But don't forget that event handlers are automatically passed a reference to the event that triggered them, so capture that in the outer handler and pass it along with your other arguments:
document.addEventListener("keyup", function(event){ searchKeyPressHandler(event, x,y,z); });
Or, if you need to utilize the function that you are setting up as the "wrapper" more than once (in the case of having to remove the listener later), you'd just declare the function with a name and pass that name into .addEventListner()
as follows:
function handler(event){
searchKeyPressHandler(event, x,y,z);
}
document.addEventListener("keyup", handler);
// And later...
document.removeEventListener("keyup", handler);