Vue CLIでVue.js + TypeScriptの構成でProvide / inject機能を使ってstore機能を実装しています。
構成
app
1/src 2├ /store 3│ ├ product.ts 4│ ├ user.ts 5│ └ index.ts 6├ App.vue 7└ main.ts
store/user.ts
typescript
1import { reactive } from "vue"; 2 3interface userStateType { 4 user: { 5 id: number; 6 name: string; 7 age: number; 8 }; 9} 10 11export const userState = () => { 12 const state = reactive({ 13 user: { 14 id: 1, 15 name: "Taro", 16 age: 18, 17 }, 18 }) as userStateType; 19 20 return { 21 state, 22 }; 23}; 24
store/product.ts
typescript
1import { reactive } from "vue"; 2 3interface productStateType { 4 product: { 5 id: number; 6 name: string; 7 price: number; 8 }; 9} 10 11export const productState = () => { 12 const state = reactive({ 13 product: { 14 id: 1, 15 name: "car", 16 price: 1000, 17 }, 18 }) as productStateType; 19 20 return { 21 state, 22 }; 23}; 24
store/index.ts
上記の user
と product
の各stateをまとめます。
typescript
1import { inject, InjectionKey } from "vue"; 2import { userState } from "./user"; 3import { productState } from "./product"; 4 5export const getStore = () => { 6 return { 7 user: userState(), 8 product: productState(), 9 }; 10}; 11 12export type storeType = ReturnType<typeof getStore>; 13 14type storesKey = keyof storeType; 15 16export const storeKey: InjectionKey<storeType> = Symbol("store"); 17 18// keyを引数で受け取って各stateを取得したい 19export function useStore(storeName: storesKey) { 20 const store = inject(storeKey); 21 if (!store) { 22 throw new Error(`Error`); 23 } 24 return store[storeName]; 25}
main.ts
typescript
1import { createApp } from "vue"; 2import App from "./App.vue"; 3import { getStore, storeKey } from "@/store/index"; 4 5createApp(App).provide(storeKey, getStore()).mount("#app");
App.vue
<template> <p>{{ userState.user.age }}</p> <p>{{ productState.product.price }}</p> </template> <script lang="ts"> import { defineComponent } from "vue"; import { useStore } from "@/store/index"; export default defineComponent({ name: "App", setup() { const { state: userState } = useStore("user"); const { state: productState } = useStore("product"); // エラー // TS2339: Property 'id' does not exist on type 'state | state'. // Property 'id' does not exist on type 'state'. console.log(userState.user.age); console.log(productState.product.price); return { userState, productState, }; }, }); </script>
発生している問題
各stateのプロパティにアクセスしようとした際に
TS2339: Property 'id' does not exist on type 'state | state'. Property 'id' does not exist on type 'state'.
上記エラーが発生します。
TypeScriptの定義(InjectionKey??)の仕方が間違っているのだとは思うのですがどなたか解決方法をご教示お願いします。
あなたの回答
tips
プレビュー