Skip to content

Add a generic type for getters too. #1896

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

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

Conversation

mat813
Copy link

@mat813 mat813 commented Dec 10, 2020

This allows you to write something like this, for example, in a vuex
module, that lives in a subdirectory of the store, where it is most
interesting:

import { GetterTree } from 'vuex';

import type { State as RootState, Getters as RootGetters } from '../';
import type { State } from './state';

export type Getters = {
  loggedIn: boolean;
  roles: string[];
  isAdmin: boolean;
};

export const getters: GetterTree<State, RootState, Getters, RootGetters> = {

And you get correct type inference in your editor.

This allows you to write something like this, for example, in a vuex
module, that lives in a subdirectory of the store, where it is most
interesting:

```
import { GetterTree } from 'vuex';

import type { State as RootState, Getters as RootGetters } from '../';
import type { State } from './state';

export type Getters = {
  loggedIn: boolean;
  roles: string[];
  isAdmin: boolean;
};

export const getters: GetterTree<State, RootState, Getters, RootGetters> = {
```

And you get correct type inference in your editor.
@mat813
Copy link
Author

mat813 commented Dec 10, 2020

And then, in your actual store that only imports modules, you would do something like:

import { createStore } from 'vuex';

import * as auth from './auth';

export type State = {
  auth: auth.State;
};

// This needs typescript 4.1
type Namespaced<T, N extends string> = {
  [P in keyof T & string as `${N}/${P}`]: T[P];
};

// Other getters are appended with a `&`
export type Getters = Namespaced<auth.Getters, 'auth'>;

export const store = createStore<State, Getters>({
  modules: {
    auth,
  },
});

(fun fact, with that, the compiler found a typo in some of my code that passed tests anyway, a new test case has been written.)

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

Successfully merging this pull request may close these issues.

1 participant