前回の記事では TypeScriptとReact の組み合わせを解説しました。
現在のフロントエンド開発では
React + TypeScript
と同じくらい
Vue + TypeScript
も一般的になっています。
Vue3ではTypeScriptが公式にサポートされており、VueプロジェクトでもTypeScriptを使うケースが増えています。
この記事では次の内容を解説します。
- VueでTypeScriptを使う理由
- Vue + TypeScriptの環境構築
- Vueコンポーネントの型
- propsの型定義
- reactive / ref の型
なぜVueでTypeScriptを使うのか
Vueアプリが大きくなると次の問題が起こります。
propsの型が不明
APIレスポンスの型が不明
状態管理が複雑
JavaScriptだけで書くと
user.name
のようなコードが
存在しないプロパティ
でもエラーにならない場合があります。
TypeScriptを使うと
props
state
API
などの型を明確にできます。
Vue + TypeScriptプロジェクト
VueではViteを使うのが一般的です。
npm create vite@latest
テンプレート
vue-ts
を選択します。
Vueコンポーネント
Vueコンポーネントは
.vue
ファイルで作成します。
例
<script setup lang="ts">
const message: string = "Hello Vue"
</script>
<template>
<h1>{{ message }}</h1>
</template>
重要なのは
lang="ts"
です。
refの型
Vueでは
ref
をよく使います。
例
import { ref } from "vue"
const count = ref<number>(0)
この場合
count
は
number
になります。
reactiveの型
オブジェクトの場合は
reactive
を使います。
例
import { reactive } from "vue"
type User = {
name: string
age: number
}
const user = reactive<User>({
name: "Taro",
age: 20
})
propsの型定義
Vueでもpropsの型を定義できます。
例
type Props = {
title: string
}
defineProps
const props = defineProps<Props>()
テンプレート
<template>
<h1>{{ props.title }}</h1>
</template>
computedの型
computedでも型を使えます。
const double = computed<number>(() => {
return count.value * 2
})
Vue + TypeScriptのメリット
VueでTypeScriptを使うメリット
型安全
propsやstateのミスを防げます。
IDE補完
VSCodeで型補完が強くなります。
大規模開発
コードの保守性が上がります。
Reactとの違い
React
JSX
Vue
Template
という違いがあります。
しかしTypeScriptの考え方は同じです。
まとめ
この記事では
VueとTypeScript
の組み合わせを解説しました。
重要なポイント
script setup + lang="ts"
ref<number>()
reactive<User>()
defineProps<Props>()
VueでもTypeScriptを使うことで、安全で保守性の高いコードを書くことができます。
次の記事
次回は
TypeScript実務パターン
を解説します。
ここでは
型設計
API型定義
プロジェクト構造
など、実務で重要な内容をまとめます。


コメント