# Vue.js + TypeScript で安心・安全にドメインの型を扱う ## Vue.js + TypeScript vue-property-decorator (vue-class-component and more) ```ts import { Component, Vue } from "vue-property-decorator"; @Component({ components: { Tasks } }) export default class TasksPage extends Vue { // data tasks: TaskEntity[] = []; // methods async fetchTasks() { const res = await api.fetchTasks(); this.tasks = res.data.map(t => new TaskEntity(t)); } } ``` または(2.5以上) ```ts export default Vue.extend({ components: { Tasks }, data() { return { tasks: [] as TaskEntity[], }; }, } ``` ![](https://i.imgur.com/wcQdtRe.png) ## TypeScript Microsoft 謹製 AltJS の一番人気(のはず) ```ts // 構造的型 interface Message { body: string; } // 型エイリアス type RawMessage = string; // Union 型 function say(message: Message | RawMessage) { //... } ``` 他にも色々便利な型指定がある ### Generics ```ts class ApiResponse<T> { public status: number; public data: T[] | T; } ``` ### Enum ```ts enum HttpResponseStatus { HTTP_OK = 200, HTTP_CREATED = 201, //... } ``` ### Function Type ```ts interface DataMapper<T, S> { map: (a: T[]) => S[]; } ``` ### 型定義ファイル ```ts export interface User { id: number; name: string; } export interface Task { id: number; title: string; status: string; created_at: string; creator: User; } ``` ## 恩恵を受けられるところ - コンパイル時に型の不一致や存在しないプロパティに対するアクセスなどに気づける - IDE (Vetur in VSCode) で補完が効くようになる - TSC (コンパイラ)によるコード最適化 ## 恩恵を受けられないところ - テンプレート(JSX を使えばあるいは…?) - Vuex はまだちょっと厳しい(Vue 3.0 になればあるいは…?) ## その他の話題 ESLint for TS ## おまけ ![](https://i.imgur.com/qFAzzup.png) 6/26(水)発売