# 7. 점진적인 타입스크립트 적용 방식 3단계 - Vuex 스토어 타입 정의 ###### tags: `지호`, `Vue.js + TypeScript 완벽 가이드` --- ## 1. 스토어의 타입 추론 문제 2개의 인터페이스를 합침 타입 스크립트 선언 병합: https://www.typescriptlang.org/docs/handbook/declaration-merging.html node_modules/vuex/vue.d.ts ```javascript= declare module "vue/types/options" { interface ComponentOptions<V extends Vue> { store?: Store<any>; } } declare module "vue/types/vue" { interface Vue { $store: Store<any>; // 스토어의 타입이 any } } ``` 스토어의 타입이 any이기 때문에, 컴포넌트 레벨에서 접근하게 되면 store의 타입이 any로 추론됨 ```javascript= this.$store.state.news // 스토어의 타입이 any이기 때문에 news가 자동완성되지 않음 ``` <br/> https://joshua1988.github.io/vue-camp/ts/vuex.html 참고하여 뷰엑스 타입 정의 ## 2. Vuex 타입 정의 방법 - state src/store/state.ts ![image](https://user-images.githubusercontent.com/24283401/164124747-827c8bec-1650-4249-a481-4036f3e3d8e7.png) src/store/index.ts ![image](https://user-images.githubusercontent.com/24283401/164124813-71a6495e-fc01-4ce5-8c21-5642c8adede7.png) node_modules/vuex/vue.d.ts 에서 any -> RootState로 변경 ```javascript= declare module "vue/types/options" { interface ComponentOptions<V extends Vue> { store?: Store<any>; } } declare module "vue/types/vue" { interface Vue { $store: Store<any>; // 스토어의 타입이 any } } ``` <br/> ## 3. Vuex 타입 정의 방법 - mutations src/store/mutations.ts - enum 사용 -> [MutationTypes.SET_NEWS] = "SET_NEWS" - Mutation은 이미 뷰에서 제공하는 타입이니 Mutations으로 타입 명명 필수 ![image](https://user-images.githubusercontent.com/24283401/164131340-e006a9ae-4766-4f1e-bc13-f4e55761ad08.png) <br/> ## 4. 스토어의 타입 추론을 위한 타입 파일 src/store/types.ts - store에서 commit 제거 - commmit에 대해서 프로젝트 레벨에서 재정의 - 스토어에서 mutation 타입 정의만 프로젝트에서 정의한 mutation으로 대체 - MyMutations - K extends keyof Mutations: mutations의 키를 받음 - P extends Parameters<Mutations[K]>[1]: mutations의 키-값의 두번째 파라미터인 payload의 타입을 가져옴 (첫번째는 state) - commit(MutationTypes.SET_NEWS, payload)왁 ㅏㅌ이 사용 가능 ![image](https://user-images.githubusercontent.com/24283401/164128679-5826722c-c8d8-4b7b-9f62-73a4ef2935fc.png) Omit: https://joshua1988.github.io/ts/usage/utility.html#%EC%9E%90%EC%A3%BC-%EC%82%AC%EC%9A%A9%EB%90%98%EB%8A%94-%EC%9C%A0%ED%8B%B8%EB%A6%AC%ED%8B%B0-%ED%83%80%EC%9E%85-%EB%AA%87-%EA%B0%9C-%EC%95%8C%EC%95%84%EB%B3%B4%EA%B8%B0 Union과 Intersection: https://joshua1988.github.io/ts/guide/operator.html#union-type <br/> node_modules/vuex/types/vue.d.ts ![image](https://user-images.githubusercontent.com/24283401/164131154-0c8d0e31-8b63-4b80-b62b-4ddca9df1dab.png) <br/> ## 5. Vuex 타입 정의 방법 - actions src/store/actions.ts ![image](https://user-images.githubusercontent.com/24283401/164132956-ac5dbc89-1ed1-4e2e-9fea-28eca49e5fb5.png) <br/> ## 6. 커스텀 타입을 프로젝트 레벨로 설정 tsconfig.json - types 폴더 안에 모든 폴더와 파일을 include ```javascript= "include": [ "src/types/**/*.d.ts" ], ``` src/types/project.d.ts ![image](https://user-images.githubusercontent.com/24283401/164187569-448eb606-a2dc-4b1a-9482-312b8d8c95c7.png)