Skip to content

Commit 4f4a5e6

Browse files
Add type inference for emitted events (#800)
* feat: TS for emitted 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 4a333dd commit 4f4a5e6

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

src/guide/typescript-support.md

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ const Component = defineComponent({
212212
type: Object as PropType<Book>,
213213
// Make sure to use arrow functions
214214
default: () => ({
215-
title: "Arrow Function Expression"
215+
title: 'Arrow Function Expression'
216216
}),
217217
validator: (book: Book) => !!book.title
218218
},
@@ -221,7 +221,7 @@ const Component = defineComponent({
221221
// Or provide an explicit this parameter
222222
default(this: void) {
223223
return {
224-
title: "Function Expression"
224+
title: 'Function Expression'
225225
}
226226
},
227227
validator(this: void, book: Book) {
@@ -232,6 +232,30 @@ const Component = defineComponent({
232232
})
233233
```
234234

235+
## Annotating emits
236+
237+
We can annotate a payload for the emitted event. Also, all non-declared emitted events will throw a type error when called:
238+
239+
```ts
240+
const Component = defineComponent({
241+
emits: {
242+
addBook(payload: { bookName: string }) {
243+
// perform runtime validation
244+
return payload.bookName.length > 0
245+
}
246+
},
247+
methods: {
248+
onSubmit() {
249+
this.$emit('addBook', {
250+
bookName: 123 // Type error!
251+
})
252+
253+
this.$emit('non-declared-event') // Type error!
254+
}
255+
}
256+
})
257+
```
258+
235259
## Using with Composition API
236260

237261
On `setup()` function, you don't need to pass a typing to `props` parameter as it will infer types from `props` component option.

0 commit comments

Comments
 (0)