# 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  src/store/index.ts  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으로 타입 명명 필수  <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)왁 ㅏㅌ이 사용 가능  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  <br/> ## 5. Vuex 타입 정의 방법 - actions src/store/actions.ts  <br/> ## 6. 커스텀 타입을 프로젝트 레벨로 설정 tsconfig.json - types 폴더 안에 모든 폴더와 파일을 include ```javascript= "include": [ "src/types/**/*.d.ts" ], ``` src/types/project.d.ts 
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up