Skip to content

Commit d38ad76

Browse files
ktsnkazupon
authored andcommitted
Translate declaring types of Vue plugins (#291)
* add a guide how to declare plugin typings (#1042) * add a guide how to declare plugin typings * improve wording * Slight tweak to working for declaring typescript types for plugins * Translate declaring types of vue plugins * Update the updated field in ts guide
1 parent cce93ab commit d38ad76

File tree

1 file changed

+61
-1
lines changed

1 file changed

+61
-1
lines changed

src/v2/guide/typescript.md

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
title: TypeScript のサポート
3-
updated: 2017-07-21
3+
updated: 2017-08-03
44
type: guide
55
order: 25
66
---
@@ -137,3 +137,63 @@ export default class MyComponent extends Vue {
137137
```
138138

139139
この構文では、コンポーネントの定義が短くなるだけでなく、明示的なインタフェース宣言がなくても `message``onClick` の型を推論することができます。この戦略では、算出プロパティ、ライフサイクルフック、描画関数の型を扱うこともできます。詳細な使用方法については、[vue-class-component のドキュメント](https://github.com/vuejs/vue-class-component#vue-class-component)を参照してください。
140+
141+
## Vue プラグインの型定義
142+
143+
プラグインは Vue のグローバル/インスタンスプロパティやコンポーネントオプションを追加することがあります。このような場合、TypeScript でそのプラグインを使用したコードをコンパイルするためには型定義が必要になります。幸い、TypeScript には[モジュール拡張(Module Argumentation)](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation)と呼ばれる、すでに存在する型を拡張する機能があります。
144+
145+
例えば、`string` 型をもつ `$myProperty` インスタンスプロパティを定義するには:
146+
147+
``` ts
148+
// 1. 拡張した型を定義する前に必ず 'vue' をインポートするようにしてください
149+
import Vue from 'vue'
150+
151+
// 2. 拡張したい型が含まれるファイルを指定してください
152+
// Vue のコンストラクタの型は types/vue.d.ts に入っています
153+
declare module 'vue/types/vue' {
154+
// 3. 拡張した Vue を定義します
155+
interface Vue {
156+
$myProperty: string
157+
}
158+
}
159+
```
160+
161+
上記のコードを(`my-property.d.ts` のような)型定義ファイルとしてあなたのプロジェクトに含めると、Vue インスタンス上で `$myProperty` が使用できるようになります。
162+
163+
```ts
164+
var vm = new Vue()
165+
console.log(vm.$myProperty) // これはうまくコンパイルされるでしょう
166+
```
167+
168+
追加でグローバルプロパティやコンポーネントオプションも定義することもできます:
169+
170+
```ts
171+
import Vue from 'vue'
172+
173+
declare module 'vue/types/vue' {
174+
// `interface` ではなく `namespace` を使うことで
175+
// グローバルプロパティを定義できます
176+
namespace Vue {
177+
const $myGlobal: string
178+
}
179+
}
180+
181+
// ComponentOptions は types/options.d.ts に定義されています
182+
declare module 'vue/types/options' {
183+
interface ComponentOptions<V extends Vue> {
184+
myOption?: string
185+
}
186+
}
187+
```
188+
189+
上記の型定義は次のコードをコンパイルできるようにします:
190+
191+
```ts
192+
// グローバルプロパティ
193+
console.log(Vue.$myGlobal)
194+
195+
// 追加のコンポーネントオプション
196+
var vm = new Vue({
197+
myOption: 'Hello'
198+
})
199+
```

0 commit comments

Comments
 (0)