Skip to content

Instantly share code, notes, and snippets.

@Klerith
Last active April 12, 2024 22:11
Show Gist options
  • Save Klerith/3c3bd3b6895e9d0672f1324d88099ece to your computer and use it in GitHub Desktop.
Save Klerith/3c3bd3b6895e9d0672f1324d88099ece 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;
@CHB94git
Copy link

Muchas gracias Fernando, empezando aquí con esta app en Typescript, Excelente curso!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment