6

What are correct Typescript types for input events in Vue? When I use Event it is missing target value or key or files properties.

Let's have an example for:

<input @input="(e: MISSING_TYPE) => {}" />
<input @keypress="(e: MISSING_TYPE) => {}" />

In React we have something like ChangeEvent which is generic and apply element specific types. How we do it in Vue?

Patryk Gułaś
  • 847
  • 1
  • 7
  • 19
  • 1
    Is KeyboardEvent what you're looking for? (Event > UIEvent > KeyboardEvent) – steve16351 Aug 28 '20 at 09:34
  • Thank you, KeyboardEvent looks good for keypress. What about input and e.target.value? Can we have any documentation on the list of these specific events like KeyboardEvent or we need to extract it from codebase? – Patryk Gułaś Aug 28 '20 at 09:36
  • 1
    `target` is on the `Event` type. I think you'd need to cast to something more specific to get value, i.e. (e.target).value – steve16351 Aug 28 '20 at 09:39
  • For docs, you have [KeyboardEvent](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent), the TypeScript types should correspond to this. You can inspect them yourself in [lib.dom.d.ts](https://github.com/microsoft/TypeScript/blob/master/lib/lib.dom.d.ts) – steve16351 Aug 28 '20 at 09:52

2 Answers2

20

Thanks to @steve16351 answer in the comments, there is summary:

For keyboard event like keypress you can use more specific event from Event -> UIEvent -> KeyboardEvent:

<input @keypress="handleKeypress" />

handleKeypress(e: KeyboardEvent) { }

For more specific event like input change on HTMLInputElement you need to cast it:

<input @input="handleInput" />

handleInput(e: Event) { 
  const target = (<HTMLInputElement>e.target)

  console.log(target.value)
}
Patryk Gułaś
  • 847
  • 1
  • 7
  • 19
0

This works for me having a common text input, whilst the accepted answer produces a linter error for me:

Error: Unexpected token. Did you mean `{'}'}` or `}`?

const onInput = (ev: Event) => {
  const { value = '' } = ev.target as HTMLInputElement;
  // ...
};
Karl Adler
  • 15,780
  • 10
  • 70
  • 88