I'm currently working on a TypeScript function that detects the "Enter" key press and, if the event.target.value's length is greater than 0, redirects to a page with that value. This code snippet is being used in a Next.js application, hence the router.push line. Here's a rough outline of the code:
const goToSearch = (e: React.KeyboardEvent<HTMLInputElement> | React.ChangeEvent<HTMLInputElement>) => {
if (e.key === "Enter") {
e.preventDefault();
if (e.target.value.length > 0) {
router.push(
{ pathname: "/Search", query: { searchVal: e.target.value } },
"/Search"
);
}
}
};
To call this function, I'm utilizing the onKeyDown prop in the input element, like so:
<input
type="search"
className="form-control border border-white"
placeholder="Search"
aria-label="Search"
onKeyDown={goToSearch}
/>
The issue arises from using TypeScript, as the event type can be either a Keyboard event or a Change Event. When attempting to provide both types using the | symbol, errors occur because TypeScript struggles to determine which event type to reference. Is there a way to define an interface or custom type that encompasses both event types (Keyboard event and Change event)? This interface or custom type would also need to account for the preventDefault void function.
Thank you