Skip to content

Add type inference for emitted events #800

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 11, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions src/guide/typescript-support.md
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ const Component = defineComponent({
type: Object as PropType<Book>,
// Make sure to use arrow functions
default: () => ({
title: "Arrow Function Expression"
title: 'Arrow Function Expression'
}),
validator: (book: Book) => !!book.title
},
Expand All @@ -221,7 +221,7 @@ const Component = defineComponent({
// Or provide an explicit this parameter
default(this: void) {
return {
title: "Function Expression"
title: 'Function Expression'
}
},
validator(this: void, book: Book) {
Expand All @@ -232,6 +232,30 @@ const Component = defineComponent({
})
```

## Annotating emits

We can annotate a payload for the emitted event. Also, all non-declared emitted events will throw a type error when called:

```ts
const Component = defineComponent({
emits: {
addBook(payload: { bookName: string }) {
// perform runtime validation
return payload.bookName.length > 0
}
},
methods: {
onSubmit() {
this.$emit('addBook', {
bookName: 123 // Type error!
})

this.$emit('non-declared-event') // Type error!
}
}
})
```

## Using with Composition API

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