From e95fd6a1a7124be0128d73e68453cd3ec15a415e Mon Sep 17 00:00:00 2001 From: HerringtonDarkholme Date: Thu, 26 Oct 2017 13:33:42 +0800 Subject: [PATCH 1/2] Recommend return type annotation --- src/v2/guide/typescript.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/v2/guide/typescript.md b/src/v2/guide/typescript.md index e7d9b61f00..36413c6059 100644 --- a/src/v2/guide/typescript.md +++ b/src/v2/guide/typescript.md @@ -139,3 +139,38 @@ var vm = new Vue({ myOption: 'Hello' }) ``` + +## Annotating Return Type + +Vue's type definition is prone to [circular reference](https://github.com/Microsoft/TypeScript/issues/12846#issuecomment-270296195) of `this`. +Annotating return type is highly recommended to avoid such error. + +```ts +import Vue, { VNode } from 'vue' + +const Component = Vue.extend({ + data() { + return { + msg: 'Hello' + } + }, + methods: { + // need annotation due to `this` in return type + greet(): string { + return this.msg + ' world' + } + }, + computed: { + // need annotation + greeting(): string { + return this.greet() + '!' + } + }, + // `createElement` is inferred, but `render` needs return type + render(createElement): VNode { + return createElement('div', this.greeting) + } +}) +``` + +If you find type inference or member completion doesn't work, you can try annotating method return type. From da1a1412f8ddc0149b625c00611c30ab972fb361 Mon Sep 17 00:00:00 2001 From: Herrington Darkholme Date: Thu, 26 Oct 2017 23:07:20 +0800 Subject: [PATCH 2/2] make explanation clear, thank @DanielRosenwasser --- src/v2/guide/typescript.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/v2/guide/typescript.md b/src/v2/guide/typescript.md index 36413c6059..8dddc833d4 100644 --- a/src/v2/guide/typescript.md +++ b/src/v2/guide/typescript.md @@ -140,10 +140,10 @@ var vm = new Vue({ }) ``` -## Annotating Return Type +## Annotating Return Types -Vue's type definition is prone to [circular reference](https://github.com/Microsoft/TypeScript/issues/12846#issuecomment-270296195) of `this`. -Annotating return type is highly recommended to avoid such error. +Because of the circular nature of Vue's declaration files, TypeScript may have difficulties inferring the types of certain methods. +For this reason, you may need to annotate the return type on methods like `render` and those in `computed`. ```ts import Vue, { VNode } from 'vue' @@ -173,4 +173,5 @@ const Component = Vue.extend({ }) ``` -If you find type inference or member completion doesn't work, you can try annotating method return type. +If you find type inference or member completion isn't working, annotating certain methods may help address these problems. +Using the `--noImplicitAny` option will help find many of these unannotated methods.