Try   HackMD

7. 점진적인 타입스크립트 적용 방식 3단계 - Vuex 스토어 타입 정의

tags: 지호, Vue.js + TypeScript 완벽 가이드

1. 스토어의 타입 추론 문제

2개의 인터페이스를 합침

타입 스크립트 선언 병합: https://www.typescriptlang.org/docs/handbook/declaration-merging.html

node_modules/vuex/vue.d.ts

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로 추론됨

this.$store.state.news // 스토어의 타입이 any이기 때문에 news가 자동완성되지 않음

https://joshua1988.github.io/vue-camp/ts/vuex.html 참고하여 뷰엑스 타입 정의

2. Vuex 타입 정의 방법 - state

src/store/state.ts

image

src/store/index.ts

image

node_modules/vuex/vue.d.ts 에서 any -> RootState로 변경

declare module "vue/types/options" { interface ComponentOptions<V extends Vue> { store?: Store<any>; } } declare module "vue/types/vue" { interface Vue { $store: Store<any>; // 스토어의 타입이 any } }

3. Vuex 타입 정의 방법 - mutations

src/store/mutations.ts

  • enum 사용 -> [MutationTypes.SET_NEWS] = "SET_NEWS"
  • Mutation은 이미 뷰에서 제공하는 타입이니 Mutations으로 타입 명명 필수

image


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

Omit: https://joshua1988.github.io/ts/usage/utility.html#자주-사용되는-유틸리티-타입-몇-개-알아보기

Union과 Intersection: https://joshua1988.github.io/ts/guide/operator.html#union-type


image


5. Vuex 타입 정의 방법 - actions

src/store/actions.ts

image


6. 커스텀 타입을 프로젝트 레벨로 설정

tsconfig.json

  • types 폴더 안에 모든 폴더와 파일을 include
"include": [ "src/types/**/*.d.ts" ],

src/types/project.d.ts

image