Skip to content

Commit e95fd6a

Browse files
Recommend return type annotation
1 parent 6919528 commit e95fd6a

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/v2/guide/typescript.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,3 +139,38 @@ var vm = new Vue({
139139
myOption: 'Hello'
140140
})
141141
```
142+
143+
## Annotating Return Type
144+
145+
Vue's type definition is prone to [circular reference](https://github.com/Microsoft/TypeScript/issues/12846#issuecomment-270296195) of `this`.
146+
Annotating return type is highly recommended to avoid such error.
147+
148+
```ts
149+
import Vue, { VNode } from 'vue'
150+
151+
const Component = Vue.extend({
152+
data() {
153+
return {
154+
msg: 'Hello'
155+
}
156+
},
157+
methods: {
158+
// need annotation due to `this` in return type
159+
greet(): string {
160+
return this.msg + ' world'
161+
}
162+
},
163+
computed: {
164+
// need annotation
165+
greeting(): string {
166+
return this.greet() + '!'
167+
}
168+
},
169+
// `createElement` is inferred, but `render` needs return type
170+
render(createElement): VNode {
171+
return createElement('div', this.greeting)
172+
}
173+
})
174+
```
175+
176+
If you find type inference or member completion doesn't work, you can try annotating method return type.

0 commit comments

Comments
 (0)