direct-vuex
direct-vuex copied to clipboard
Typed mapGetters / mapActions for Vuex 3 (vue 2)
Hello, First of all thanks for your lib. I have implemented typed getters and actions in my project so i want to share code with you so you could update your lib (v2) if possible :) Feel free to make it better :)
import store from '@/store';
import { mapActions, mapGetters, mapState } from 'vuex';
// Getters
type TGetterKey = keyof typeof store.getters;
type TGetterModule<T extends TGetterKey> = typeof store.getters[T];
type TGetterFuncs<T extends TGetterKey> = keyof TGetterModule<T>;
type TGetterResult<
T extends TGetterKey = TGetterKey,
N extends TGetterFuncs<T> = TGetterFuncs<T>,
> = typeof store.getters[T][N];
export const mapTypedGetters = <
T extends TGetterKey,
N extends TGetterFuncs<T>,
>(
namespace: T,
keys: N[],
): {
[K in N]: () => TGetterResult<T, K>;
} => {
return mapGetters(namespace, keys as any) as any;
};
// State
type TStateKey = keyof typeof store.state;
type TStateModule<T extends TStateKey> = typeof store.state[T];
type TStateFuncs<T extends TStateKey> = keyof TStateModule<T>;
type TStateResult<
T extends TStateKey = TStateKey,
N extends TStateFuncs<T> = TStateFuncs<T>,
> = typeof store.state[T][N];
export const mapTypedState = <T extends TStateKey, N extends TStateFuncs<T>>(
namespace: T,
keys: N[],
): {
[K in N]: () => TStateResult<T, K>;
} => {
return mapState(namespace, keys as any) as any;
};
// Actions
export type TActionKey = keyof typeof store.dispatch;
export type TActionModule<T extends TActionKey> = typeof store.dispatch[T];
export type TActionFuncs<T extends TActionKey> = keyof TActionModule<T>;
type TActionResult<
T extends TActionKey = TActionKey,
N extends TActionFuncs<T> = TActionFuncs<T>,
> = typeof store.dispatch[T][N];
export const mapTypedActions = <
T extends TActionKey,
N extends TActionFuncs<T>,
>(
namespace: T,
keys: N[],
): {
[K in N]: TActionResult<T, K>;
} => {
return mapActions(namespace, keys as any) as any;
};