What are types for input events in Vue
Asked Answered
F

2

10

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?

Futures answered 28/8, 2020 at 9:27 Comment(4)
Is KeyboardEvent what you're looking for? (Event > UIEvent > KeyboardEvent)Amati
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?Portray
target is on the Event type. I think you'd need to cast to something more specific to get value, i.e. (<HTMLInputElement>e.target).valueAmati
For docs, you have KeyboardEvent, the TypeScript types should correspond to this. You can inspect them yourself in lib.dom.d.tsAmati
F
27

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)
}
Futures answered 28/8, 2020 at 9:49 Comment(1)
this works for me, though I had to cast the target as: const target = e.target as HTMLInputElementLassa
A
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;
  // ...
};
Amherst answered 27/6, 2023 at 6:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.