Skip to content

Add TypeScript example for event handling #927

Closed
@TheDutchCoder

Description

@TheDutchCoder

Since a lot of developers will be dealing with event handling in their apps, it would be a good idea to add some documentation around this when doing event handling in combination with TypeScript.

To give an example, consider the following snippets:

<template>
  <input type="text" @change="handleChange" />
</template>

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  setup () {
    const handleChange = (evt) => { // `evt` will be of type `any`
      console.log(evt.target.value) // TS will throw an error here
    }

    return { handleChange }
  }
})
</script>

Here evt.target.value will throw a TypeScript error, because the event passed by the Vue template isn't typed.
Strictly speaking this might not be Vue's job, since it's a native DOM event, but developers might wonder what's going on.

The solution, currently, is to cast the event target like so:

    const handleChange = (evt: Event) => {
      console.log((evt.target as HTMLInputElement).value)
    }

I think it would be beneficial to add that to the docs somewhere.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions