How can I detect when the enter key is pressed in a form element in Typescript by attaching a keypress event?
Below is the code from my index.ts
file:
const search_field = document.querySelector('#search-field');
search_field?.addEventListener('keypress', (event) => {
const target = event.target as HTMLInputElement;
if (event.key === 'Enter') {
console.log('Searching for: ' + target.value);
}
});
However, webpack is showing the following error:
TS2339: Property 'key' does not exist on type 'Event'.
I came across a solution to cast the event to a KeyboardEvent
type on Stack Overflow. So I made the following changes:
const search_field = document.querySelector('#search-field');
search_field?.addEventListener('keypress', (event:e:KeyboardEvent) => {
const target = event.target as HTMLInputElement;
if (event.key === 'Enter') {
console.log('Searching for: ' + target.value);
}
});
Unfortunately, this modification resulted in the error:
TS2769: No overload matches this call.
Overload 1 of 2, '(type: keyof ElementEventMap, listener: (this: Element, ev: Event) => any, options?: boolean | AddEventListenerOptions | undefined): void | undefined', gave the following error.
Argument of type 'keypress' is not assignable to parameter of type 'keyof ElementEventMap'.
Overload 2 of 2, '(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void | undefined', gave the following error.
Argument of type '(event: KeyboardEvent) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
Type '(event: KeyboardEvent) => void' is not assignable to type 'EventListener'.
Types of parameters 'event' and 'evt' are incompatible.
Type 'Event' is missing properties like altKey, charCode, code, ctrlKey, and more.