strong type check for vuex
npm install vuex-with-type#### State
!state.gif
#### Commit
!commit.gif
#### Dispatch
!dispatch.gif
$store的类型推断写为了Store,这导致我们后续的声明合并``shell`
npm install vuex-with-type
shell
npx vwt init
`全局使用
vwt命令:
- vwt handbook 👉 查看所有命令说明
- ~~vwt config 👉 生成配置文件 以配置文件的形式进行源码生成~~
- vwt init 👉 初始化并生成声明文件 如果有config命令生成的文件,则会优先使用它$3
- store/index.ts:
`typescript
import Vue from 'vue'
import Vuex, { Commit } from 'vuex'
import { isOwnKey, NonNeverState, GetState, GetMutationKeyParamMap, GetActionKeyParamMap } from "vuex-with-type";Vue.use(Vuex)
const state = {
token: "",
openId: "",
name: "",
appId: "1"
}
// 将vuex store独立出来
const storeOptions = {
state,
mutations: {
SET_STATE(s: NonNeverState, obj: Partial>) {
for (const key in obj) {
if (isOwnKey(key, obj)) {
s[key] = obj[key];
}
}
},
SET_NAME(s: NonNeverState, v: string) {
s.name = v;
}
},
actions: {
SET_ASYNC_STATE({ commit }: { commit: Commit }, obj: Partial>) {
return new Promise(resolve=> {
setTimeout(()=> {
commit("SET_STATE", obj);
resolve(obj);
});
});
}
},
modules: {
modOne: { ... },
modTwo: { ... }
}
};
/** TState TMutation TAction(如果有的话) 必须要导出,当然你可以不叫这个名字,但必须在
* 自动生成的声明文件中对应
*/
export type TState = NonNeverState>
/**
* @description mutation类型,能够推断出嵌套的modules:
* {
* SET_XXX: typeof second param;
* module/SET_XX: typeof second param;
* module/moduleSon/SET_X: typeof second param
* }
*/
export type TMutation = GetMutationKeyParamMap;
export type TAction = GetActionKeyParamMap;
const store = new Vuex.Store(storeOptions);
export default store;
`effect
vuex-with-type is to solve the problem that vuex4 and lower versions cannot correctly infer the type when writing typescript. For now, I only wrote the type inference of state and mutation for the time being.
prieiple
The essential reason why the type cannot be correctly inferred under vuex4 is because the official vuex declaration file writes the type inference of $store as Store when merging Vue, which leads to the merger of our subsequent declarations
Neither can narrow the type, so the type of state is any, and the type of commit cannot be accurately inferred. My method is very simple. Reading this declaration file of vuex in node_modules then delete extra part.Then generate a declaration file that can accurately infer the state and commit automatically.install
`shell
npm install vuex-with-type
`usage
`shell
npx vwt init
`Use the
vwt` command globally:if everything is ok, you can get correct type now.
This is my first time writing an open source library, Sorry for not doing well.