It so happened that I started learning Vue a month ago with Vue 3. It was previously announced that Vue 3 was rewritten in typescript. To be honest, I expected the same from the new version of Vuex 4 for Vue 3.
But for some reason, everything turned out not as expected. By looking at the Vuex 4 repository
https://github.com/vuejs/vuex/tree/4.0
We will suddenly see that it is written in js and at the very end types are written for the ready-made code.
On the one hand, we, as users, in theory do not care how the code is written - the main thing is that it is convenient to use it. And this is where a novice user immediately finds himself in a strange situation when trying to use typescript to control types for the created store objects. The fact is that the typing of the created store in Vuex 4 is absent from the word at all.
Well, okay, I thought and started looking for a solution.
For VUE 2, elegant decorator-based solutions are offered, such as this . If we look at the source code of the project, we will see that it was developed for "vue": "> = 2" and "vuex": "3"
The use of decorators in Vue 3 is based on the vue-class-component library , which currently hasn't even been documented. Thus, using decorators for typing Vuex 4 for Vue 3 looks like a complicated undertaking in my opinion at the moment and I decided to abandon the use of decorators for typing.
The solution I suggest is based on the project and article .
The method proposed by Andrey, in my opinion, requires a large amount of additional code, and based on his code, I implemented my solution.
Highlights
store " ", . - . , - auth.ts auth. - ( - typescript ).
Vuex .
Vuex Omit Vuex , actions getters.
store - index.ts ( Vuex ) ( counter auth).
mutatations mutations void. Actions payload , action. typescript 4 - named tupples. - , , index.
typescript 4 - package.json.
vue-cli typescript 3 .
ncu package.json > 4.0 ( typescript 4.1.3 ). package-lock.json npm install.
. src store - . typescript >= 4
initialState.ts - state. state , typescript infer . , - - users:
export const initialState = {
counter: {
counter: 0,
},
auth: {
name: "Ivan",
idUser: "89annsdj77",
email: "ivan@ivan.ru",
users:[] as Array<string>
},
};
- index.ts - "no change code " .
modules - ( Vuex - ).
(), . Actions no change code .
Getters, ActionsPayload, MutationPayload , counter.ts
mutations, getters, actionsactions
HelloWorld.
P.S. - github.