Skip to content

docs: add a guide to annotate component type in decorator #450

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 1 commit into from
Sep 14, 2020
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
3 changes: 2 additions & 1 deletion docs/.vuepress/config.js
Original file line number Diff line number Diff line change
@@ -44,7 +44,8 @@ module.exports = {
'guide/props-definition.md',
'guide/property-type-declaration.md',
'guide/refs-type-extension.md',
'guide/hooks-auto-complete.md'
'guide/hooks-auto-complete.md',
'guide/annotate-component-type-in-decorator'
]
}
]
45 changes: 45 additions & 0 deletions docs/guide/annotate-component-type-in-decorator.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Annotate Component Type in Decorator

There are cases that you want to use your component type on a function in `@Component` decorator argument.
For example, to access component methods in a watch handler:

```ts
@Component({
watch: {
postId(id: string) {
// To fetch post data when the id is changed.
this.fetchPost(id) // -> Property 'fetchPost' does not exist on type 'Vue'.
}
}
})
class Post extends Vue {
postId: string

fetchPost(postId: string): Promise<void> {
// ...
}
}
```

The above code produces a type error that indicates `fetchPost` does not exist on `this` in the watch handler. This happens because `this` type in `@Component` decorator argument is the base `Vue` type.

To use your own component type (in this case `Post`), you can annotate the decorator through its type parameter.

```ts
// Annotate the decorator with the component type 'Post' so that `this` type in
// the decorator argument becomes 'Post'.
@Component<Post>({
watch: {
postId(id: string) {
this.fetchPost(id) // -> No errors
}
}
})
class Post extends Vue {
postId: string

fetchPost(postId: string): Promise<void> {
// ...
}
}
```