Skip to content

Instantly share code, notes, and snippets.

@OscarGM40
Forked from Klerith/index.ts
Created April 3, 2023 10:15
Show Gist options
  • Save OscarGM40/0adf09e758ad2a9329a34428bc6a6c27 to your computer and use it in GitHub Desktop.
Save OscarGM40/0adf09e758ad2a9329a34428bc6a6c27 to your computer and use it in GitHub Desktop.
Vuex + TypeScript - Store Structure Strongly Typed
import { createStore } from 'vuex';
// My custom modules
import exampleModule from './module-template';
import { ExampleStateInterface } from './module-template/state';
export interface StateInterface {
// Define your own store structure, using submodules if needed
// example: ExampleStateInterface;
// Declared as unknown to avoid linting issue. Best to strongly type as per the line above.
example: ExampleStateInterface
}
export default createStore<StateInterface>({
modules: {
example: exampleModule
}
})
import { ActionTree } from 'vuex';
import { ExampleStateInterface } from './state';
import { StateInterface } from '../index';
const actions: ActionTree<ExampleStateInterface, StateInterface> = {
someAction( /*{ commit }, payload */ ) {
// a line to prevent linter errors
}
}
export default actions;
import { GetterTree } from 'vuex';
import { ExampleStateInterface } from './state';
import { StateInterface } from '../index';
const getters: GetterTree<ExampleStateInterface, StateInterface> = {
someGetter( /* state */ ) {
// return true;
}
}
export default getters;
import { Module } from 'vuex';
import { StateInterface } from '../index';
import state, { ExampleStateInterface } from './state';
import actions from './actions';
import getters from './getters';
import mutations from './mutations';
const exampleModule: Module<ExampleStateInterface, StateInterface> = {
namespaced: true,
actions,
getters,
mutations,
state
}
export default exampleModule;
import { MutationTree } from 'vuex';
import { ExampleStateInterface } from './state';
const mutation: MutationTree<ExampleStateInterface> = {
someMutation( /* state: ExampleStateInterface */) {
// a line to prevent linter errors
}
}
export default mutation;
export interface ExampleStateInterface {
prop: boolean;
}
function state(): ExampleStateInterface {
return {
prop: true,
}
}
export default state;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment