vuex-typed-helper
v1.1.0
Published
vuex typescript commit, dispatch, getters, modules prompt
Downloads
116
Maintainers
Readme
vuex 类型推断工具
使用方法, 在下列示例中 commit,dispatch, getter 将会受到严格的类型校验
如需要使用modules的类型推断,请参考example目录下的代码
import type {
TypedDispatch,
TypedCommit,
GetGetterContext,
GetActionContext,
GetState,
CreateStoreItem,
GetGlobalGetterFn
} from 'vuex-typed-helper';
interface State {
local: boolean
}
interface Actions {
test(ctx: GetActionContext<StoreItem>, payload: number): Promise<number>;
otherTest(ctx: GetActionContext<StoreItem>, payload: number): number;
}
interface Mutations {
say(state: GetState<StoreItem>, payload: number): void;
otherSay(state: GetState<StoreItem>, payload: number): void;
}
interface Getters {
someValue(...args: GetGetterContext<StoreItem>): number;
otherValue(...args: GetGetterContext<StoreItem>): () => number;
}
export type StoreItem = CreateStoreItem<State, Mutations, Actions, Getters>;
const state: State = {
local: false,
}
const actions: Actions = {
test ({ dispatch, commit, getters }, payload) {
commit('say', 12)
return Promise.resolve(getters.someValue);
},
otherTest() {
return 1;
}
};
const mutations: Mutations = {
say(state, payload) {
state.local;
console.log(payload);
},
otherSay(state, payload) {
state.local;
console.log(payload);
},
};
const getters: Getters = {
someValue(state, getters, rootState) {
return 1;
},
otherValue(state, getters, rootState) {
return () => {
return getters.someValue + 4;
};
},
};
const store = createStore({
state: state as GetState<StoreItem>,
mutations: mutations as any,
getters: getters as any,
actions: actions as any,
});
export const useStore = () => {
return store;
}
export const commit: TypedCommit<StoreItem> = (type, payload?, options?) => {
return store.commit(type, payload, options) as any;
}
export const dispatch: TypedDispatch<StoreItem> = (type, payload?, options?) => {
return store.dispatch(type, payload, options) as any;
}
export const getter: GetGlobalGetterFn<StoreItem> = (key) => {
return store.getters[key];
}
getter('someValue'); // number
dispatch('test', 12); // Promise<number>
commit('say', 21); // void