Skip to content
Type level helper to ensure type safety in Vuex
TypeScript
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
test refactor: format Feb 13, 2019
.gitignore Init Aug 26, 2017
README.md docs: fix incorrect import target Aug 26, 2017
helpers.d.ts refactor: format Feb 13, 2019
index.d.ts Type this parameter for DefineActions (#8) Apr 10, 2019
package-lock.json 1.2.2 Apr 10, 2019
package.json 1.2.2 Apr 10, 2019
tsconfig.json chore: add test command Aug 26, 2017

README.md

Vuex Type Helper

Type level helper to ensure type safety in Vuex.

Installation

# npm
$ npm install vuex-type-helper

# yarn
$ yarn add vuex-type-helper

Example

import * as Vuex from 'vuex'
import { DefineGetters, DefineMutations, DefineActions, Dispatcher, Committer } from 'vuex-type-helper'

/**
 * Declare module types
 */
export interface CounterState {
  count: number
}

export interface CounterGetters {
  // getterName: returnType
  half: number
}

export interface CounterMutations {
  // mutationName: mutationPayloadType
  inc: {
    amount: number
  }
}

export interface CounterActions {
  // actionName: actionPayloadType
  incAsync: {
    amount: number
    delay: number
  }
}

/**
 * Implement the module
 */
const state: CounterState = {
  count: 0
}

const getters: DefineGetters<CounterGetters, CounterState> = {
  half: state => state.count / 2
}

const mutations: DefineMutations<CounterMutations, CounterState> = {
  inc (state, { amount }) {
    state.count += amount
  }
}

const actions: DefineActions<CounterActions, CounterState, CounterMutations, CounterGetters> = {
  incAsync ({ commit }, payload) {
    setTimeout(() => {
      commit('inc', payload)
    }, payload.delay)
  }
}

/**
 * Create a store as same as the ordinary way
 */
const store = new Vuex.Store({
  state,
  getters,
  mutations,
  actions
})

/**
 * Annotate dispatch/commit type with declared actions/mutations type
 */
store.dispatch<Dispatcher<CounterActions>>({
  type: 'incAsync',
  amount: 1,
  delay: 1000
})

store.commit<Committer<CounterMutations>>({
  type: 'inc',
  amount: 1
})

License

MIT

You can’t perform that action at this time.