Skip to content

Commit 2e20116

Browse files
Add TypeScript example for event handling (#1114)
* feat: add typing native events * Update src/guide/typescript-support.md Co-authored-by: skirtle <65301168+skirtles-code@users.noreply.github.com> Co-authored-by: skirtle <65301168+skirtles-code@users.noreply.github.com>
1 parent f3eb270 commit 2e20116

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

src/guide/typescript-support.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -486,3 +486,36 @@ export default defineComponent({
486486
}
487487
})
488488
```
489+
490+
### Typing Event Handlers
491+
492+
When dealing with native DOM events, it might be useful to type the argument we pass to the handler correctly. Let's take a look at this example:
493+
494+
```vue
495+
<template>
496+
<input type="text" @change="handleChange" />
497+
</template>
498+
499+
<script lang="ts">
500+
import { defineComponent } from 'vue'
501+
502+
export default defineComponent({
503+
setup() {
504+
// `evt` will be of type `any`
505+
const handleChange = evt => {
506+
console.log(evt.target.value) // TS will throw an error here
507+
}
508+
509+
return { handleChange }
510+
}
511+
})
512+
</script>
513+
```
514+
515+
As you can see, without annotating the `evt` argument correctly, TypeScript will throw an error when we try to access the value of the `<input>` element. The solution is to cast the event target with a correct type:
516+
517+
```ts
518+
const handleChange = (evt: Event) => {
519+
console.log((evt.target as HTMLInputElement).value)
520+
}
521+
```

0 commit comments

Comments
 (0)