Skip to content

Commit 9daa352

Browse files
authored
Guide > Tooling > TypeScript Support の翻訳を追従 (#297)
* fix: remove original * Correct typo in "Single file components" reference vuejs/docs@365d370#diff-c8904f42c96ea728eea302e9bc39484fbb58d2401b4017ad37ea848fc8f183e5 * Add TypeScript + Webpack Configuration Tip vuejs/docs@80ddbb7#diff-c8904f42c96ea728eea302e9bc39484fbb58d2401b4017ad37ea848fc8f183e5 * docs(ts-support): annotating props with validators and default values vuejs/docs@7e65f12#diff-c8904f42c96ea728eea302e9bc39484fbb58d2401b4017ad37ea848fc8f183e5 * Add type inference for emitted events vuejs/docs@4f4a5e6#diff-c8904f42c96ea728eea302e9bc39484fbb58d2401b4017ad37ea848fc8f183e5 * fix: fixed emits heading vuejs/docs@eac3457#diff-c8904f42c96ea728eea302e9bc39484fbb58d2401b4017ad37ea848fc8f183e5 * docs: mention TSX support and how to enable it with Vue CLI vuejs/docs@438189a#diff-c8904f42c96ea728eea302e9bc39484fbb58d2401b4017ad37ea848fc8f183e5 * Add an example of using defineComponent in a single-file component vuejs/docs@8eaf11b#diff-c8904f42c96ea728eea302e9bc39484fbb58d2401b4017ad37ea848fc8f183e5 * docs: Add type definition for globalProperties in TypeScript chapter vuejs/docs@8c9ebf1#diff-c8904f42c96ea728eea302e9bc39484fbb58d2401b4017ad37ea848fc8f183e5 * docs: translate typescript support * fix: translate 'Annotaging xxx'
1 parent a25a888 commit 9daa352

File tree

1 file changed

+162
-15
lines changed

1 file changed

+162
-15
lines changed

src/guide/typescript-support.md

Lines changed: 162 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,31 @@
2626

2727
より詳細を知るためには、[TypeScript compiler options docs](https://www.typescriptlang.org/docs/handbook/compiler-options.html) を参照してください。
2828

29+
## Webpack の設定
30+
31+
カスタムの Webpack の設定を使っている場合、 `.vue` ファイルの `<script lang="ts">` ブロックをパースするように `ts-loader` を設定する必要があります:
32+
33+
```js{10}
34+
// webpack.config.js
35+
module.exports = {
36+
...
37+
module: {
38+
rules: [
39+
{
40+
test: /\.tsx?$/,
41+
loader: 'ts-loader',
42+
options: {
43+
appendTsSuffixTo: [/\.vue$/],
44+
},
45+
exclude: /node_modules/,
46+
},
47+
{
48+
test: /\.vue$/,
49+
loader: 'vue-loader',
50+
}
51+
...
52+
```
53+
2954
## 開発ツール
3055

3156
### プロジェクトの作成
@@ -51,9 +76,17 @@ vue add typescript
5176
</script>
5277
```
5378

79+
また、TypeScript と [JSX `render` 関数](/guide/render-function.html#jsx) を組み合わせたい場合:
80+
81+
```html
82+
<script lang="tsx">
83+
...
84+
</script>
85+
```
86+
5487
### エディタによるサポート
5588

56-
TypeScript による Vue アプリケーションの開発のために、すぐに利用できる TypeScript サポートを提供している [Visual Studio Code](https://code.visualstudio.com/) を強く推奨します。[単一ファイルコンポーネント](./single-file-components.html) (SFCs) を使用している場合、SFC 内部での TypeScript の推論やその他の優れた機能を提供している、素晴らしい [Vetur エクステンション](https://github.com/vuejs/vetur) を入手してください。
89+
TypeScript による Vue アプリケーションの開発のために、すぐに利用できる TypeScript サポートを提供している [Visual Studio Code](https://code.visualstudio.com/) を強く推奨します。[単一ファイルコンポーネント](./single-file-component.html) (SFCs) を使用している場合、SFC 内部での TypeScript の推論やその他の優れた機能を提供している、素晴らしい [Vetur エクステンション](https://github.com/vuejs/vetur) を入手してください。
5790

5891
[WebStorm](https://www.jetbrains.com/webstorm/) もすぐに利用できる TypeScript と Vue のサポートを提供しています。
5992

@@ -69,6 +102,18 @@ const Component = defineComponent({
69102
})
70103
```
71104

105+
[単一ファイルコンポーネント](/guide/single-file-component.html) を使っている場合、これは一般的に次のように書かれます:
106+
107+
```vue
108+
<script lang="ts">
109+
import { defineComponent } from 'vue'
110+
111+
export default defineComponent({
112+
// type inference enabled
113+
})
114+
</script>
115+
```
116+
72117
## オプション API とともに使用する
73118

74119
TypeScript は明示的に型を定義することなく、ほとんどの型を推論できるようにあるべきです。例えば、数値である `count` プロパティを持つコンポーネントがある場合、文字列に特有のメソッドを呼び出すとエラーになります:
@@ -108,6 +153,52 @@ const Component = defineComponent({
108153
})
109154
```
110155

156+
### `globalProperties` のための型の拡張
157+
158+
Vue 3 には [`globalProperties` オブジェクト](../api/application-config.html#globalproperties) が用意されていて、任意のコンポーネントインスタンスからアクセス可能なグローバルプロパティを追加するために使用できます。例えば、 [プラグイン](./plugins.html#プラグインを書く) では共有されたグローバルオブジェクトや関数を注入したい場合があります。
159+
160+
```ts
161+
// ユーザの定義
162+
import axios from 'axios'
163+
164+
const app = Vue.createApp({})
165+
app.config.globalProperties.$http = axios
166+
167+
// あるデータを検証するためのプラグイン
168+
export default {
169+
install(app, options) {
170+
app.config.globalProperties.$validate = (data: object, rule: object) => {
171+
// 対象のデータが特定のルールを満たしているかチェック
172+
}
173+
}
174+
}
175+
```
176+
177+
これらの新しいプロパティを TypeScript に伝えるために、[Module Augmentation](https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation) を使うことができます。
178+
179+
上記の例では、次のような型宣言を追加することができます:
180+
181+
```ts
182+
import axios from 'axios'
183+
184+
declare module '@vue/runtime-core' {
185+
export interface ComponentCustomProperties {
186+
$http: typeof axios
187+
$validate: (data: object, rule: object) => boolean
188+
}
189+
}
190+
```
191+
192+
この型宣言は同じファイル、またはプロジェクト全体の `*.d.ts` ファイル(例えば、 TypeScript で自動的に読み込まれる `src/typings` フォルダの中)に記述することができます。ライブラリやプラグインの作者は、このファイルを `package.json``types` プロパティで指定します。
193+
194+
::: warning 宣言ファイルが TypeScript モジュールであることを確認
195+
Module Augmentation を利用するためには、ファイルの中に少なくとも1つのトップレベルの `import``export` があることを確認する必要があります。それが単に `export {}` であってもです。
196+
197+
[TypeScript](https://www.typescriptlang.org/docs/handbook/modules.html) では、トップレベルの `import``export` を含むファイルはすべて「モジュール」とみなされます。モジュールの外で型宣言が行われた場合、元の型を拡張するのではなく、上書きしてしまいます。
198+
:::
199+
200+
`ComponentCustomProperties` 型について詳しくは、[`@vue/runtime-core` での定義](https://github.com/vuejs/vue-next/blob/2587f36fe311359e2e34f40e8e47d2eebfab7f42/packages/runtime-core/src/componentOptions.ts#L64-L80) と、[TypeScript ユニットテスト](https://github.com/vuejs/vue-next/blob/master/test-dts/componentTypeExtensions.test-d.tsx) を参照してください。
201+
111202
### 戻り値の型にアノテーションをつける
112203

113204
Vue の型宣言ファイルの循環的な性質により、TypeScript は算出プロパティの型を推論することが困難な場合があります。この理由により、算出プロパティの戻り値の型にアノテーションをつける必要があります。
@@ -125,7 +216,7 @@ const Component = defineComponent({
125216
// アノテーションが必要です
126217
greeting(): string {
127218
return this.message + '!'
128-
}
219+
},
129220

130221
// セッターを持つ算出プロパティのでは、ゲッターにアノテーションが必要です
131222
greetingUppercased: {
@@ -134,8 +225,8 @@ const Component = defineComponent({
134225
},
135226
set(newValue: string) {
136227
this.message = newValue.toUpperCase();
137-
},
138-
},
228+
}
229+
}
139230
}
140231
})
141232
```
@@ -147,34 +238,91 @@ Vue は `type` が定義されたプロパティについてランタイムバ
147238
```ts
148239
import { defineComponent, PropType } from 'vue'
149240

150-
interface ComplexMessage {
241+
interface Book {
151242
title: string
152-
okMessage: string
153-
cancelMessage: string
243+
author: string
244+
year: number
154245
}
246+
155247
const Component = defineComponent({
156248
props: {
157249
name: String,
158250
success: { type: String },
159251
callback: {
160252
type: Function as PropType<() => void>
161253
},
162-
message: {
163-
type: Object as PropType<ComplexMessage>,
164-
required: true,
165-
validator(message: ComplexMessage) {
166-
return !!message.title
254+
book: {
255+
type: Object as PropType<Book>,
256+
required: true
257+
}
258+
}
259+
})
260+
```
261+
262+
::: warning
263+
TypeScript には、関数式の型推論に [設計上の制限](https://github.com/microsoft/TypeScript/issues/38845) があるため、 `validators` と、オブジェクトや配列の `default` 値に注意する必要があります:
264+
:::
265+
266+
```ts
267+
import { defineComponent, PropType } from 'vue'
268+
269+
interface Book {
270+
title: string
271+
year?: number
272+
}
273+
274+
const Component = defineComponent({
275+
props: {
276+
bookA: {
277+
type: Object as PropType<Book>,
278+
// 必ずアロー関数を使うこと
279+
default: () => ({
280+
title: 'Arrow Function Expression'
281+
}),
282+
validator: (book: Book) => !!book.title
283+
},
284+
bookB: {
285+
type: Object as PropType<Book>,
286+
// または明示的にこのパラメータを提供する
287+
default(this: void) {
288+
return {
289+
title: 'Function Expression'
290+
}
291+
},
292+
validator(this: void, book: Book) {
293+
return !!book.title
167294
}
168295
}
169296
}
170297
})
171298
```
172299

173-
バリデータの型推論やメンバの補完が機能していない場合、引数に期待される型のアノテーションをつけることで問題に対処できるかもしれません。
300+
### emits にアノテーションをつける
301+
302+
発行されたイベントのペイロードにアノテーションをつけることができます。また、すべての宣言されていない発行されたイベントは、呼び出されたときに型エラーが発生します:
303+
304+
```ts
305+
const Component = defineComponent({
306+
emits: {
307+
addBook(payload: { bookName: string }) {
308+
// ランタイムバリデーションの実行
309+
return payload.bookName.length > 0
310+
}
311+
},
312+
methods: {
313+
onSubmit() {
314+
this.$emit('addBook', {
315+
bookName: 123 // 型エラー!
316+
})
317+
318+
this.$emit('non-declared-event') // 型エラー!
319+
}
320+
}
321+
})
322+
```
174323

175324
## コンポジション API とともに使用する
176325

177-
On `setup()` function, you don't need to pass a typing to `props` parameter as it will infer types from `props` component option.
178326
`setup()` 関数においては、`props` 引数に型をつける必要はありません。`setup()` 関数は `props` コンポーネントオプションから型を推論するからです。
179327

180328
```ts
@@ -197,7 +345,6 @@ const Component = defineComponent({
197345

198346
### `ref` を型定義する
199347

200-
Refs infer the type from the initial value:
201348
Ref は初期値から肩を推論します:
202349

203350
```ts

0 commit comments

Comments
 (0)