Skip to content

Commit d7b1cc3

Browse files
ktsnchrisvfritz
authored andcommitted
add a guide how to declare plugin typings (vuejs#1042)
* add a guide how to declare plugin typings * improve wording * Slight tweak to working for declaring typescript types for plugins
1 parent 9f4f756 commit d7b1cc3

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

src/v2/guide/typescript.md

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -137,3 +137,63 @@ export default class MyComponent extends Vue {
137137
```
138138

139139
With this syntax alternative, our component definition is not only shorter, but TypeScript can also infer the types of `message` and `onClick` without explicit interface declarations. This strategy even allows you to handle types for computed properties, lifecycle hooks, and render functions. For full usage details, see [the vue-class-component docs](https://github.com/vuejs/vue-class-component#vue-class-component).
140+
141+
## Declaring Types of Vue Plugins
142+
143+
Plugins may add to Vue's global/instance properties and component options. In these cases, type declarations are needed to make plugins compile in TypeScript. Fortunately, there's a TypeScript feature to augment existing types called [module augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation).
144+
145+
For example, to declare an instance property `$myProperty` with type `string`:
146+
147+
``` ts
148+
// 1. Make sure to import 'vue' before declaring augmented types
149+
import Vue from 'vue'
150+
151+
// 2. Specify a file with the types you want to augment
152+
// Vue has the constructor type in types/vue.d.ts
153+
declare module 'vue/types/vue' {
154+
// 3. Declare augmentation for Vue
155+
interface Vue {
156+
$myProperty: string
157+
}
158+
}
159+
```
160+
161+
After including the above code as a declaration file (like `my-property.d.ts`) in your project, you can use `$myProperty` on a Vue instance.
162+
163+
```ts
164+
var vm = new Vue()
165+
console.log(vm.$myProperty) // This will be successfully compiled
166+
```
167+
168+
You can also declare additional global properties and component options:
169+
170+
```ts
171+
import Vue from 'vue'
172+
173+
declare module 'vue/types/vue' {
174+
// Global properties can be declared
175+
// by using `namespace` instead of `interface`
176+
namespace Vue {
177+
const $myGlobal: string
178+
}
179+
}
180+
181+
// ComponentOptions is declared in types/options.d.ts
182+
declare module 'vue/types/options' {
183+
interface ComponentOptions<V extends Vue> {
184+
myOption?: string
185+
}
186+
}
187+
```
188+
189+
The above declarations allow the following code to be compiled:
190+
191+
```ts
192+
// Global property
193+
console.log(Vue.$myGlobal)
194+
195+
// Additional component option
196+
var vm = new Vue({
197+
myOption: 'Hello'
198+
})
199+
```

0 commit comments

Comments
 (0)