Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Typed mapGetters / mapActions for Vuex 3 (vue 2) #75

Open
ushinnary opened this issue Dec 7, 2022 · 0 comments
Open

Typed mapGetters / mapActions for Vuex 3 (vue 2) #75

ushinnary opened this issue Dec 7, 2022 · 0 comments

Comments

@ushinnary
Copy link

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;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant