Home > Back-end >  How to listen for an enter keypress from Typescript
How to listen for an enter keypress from Typescript

Time:07-21

How do you attach a keypress event to a form element so you can detect when the enter key is pressed in Typescript?

My index.ts looks like:

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);
  }
});

but webpack is giving me the error:

TS2339: Property 'key' does not exist on type 'Event'.

This similar question suggests casting the event to a KeyboardEvent type. So I tried:

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);
  }
});

but that just gives me 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 the following properties from type 'KeyboardEvent': altKey, charCode, code, ctrlKey, and 17 more.

CodePudding user response:

The issue you're dealing with relates to EventTarget since event.target does not inherit from Element (reason being event.target could potentially be a XMLHttpRequest, AudioNode, etc).

A potential workaround could be utilizing instanceof to ensure target is the expected type:

const search_field = document.querySelector('#search-field');

search_field?.addEventListener('keypress', (event) => {
  // check if event.target is instanceof HTMLInputElement
  // this check tells typescript to then treat "event.target" as an HTMLInputElement

  if (event.key === 'Enter' && event.target instanceof HTMLInputElement) {
      console.log('searching for:' event.target.value);
  }
});

  • Related