https://github.com/ktsn/vuex-type-helper
Type level helper to ensure type safety in Vuex
https://github.com/ktsn/vuex-type-helper
type type-safety typescript vue vuex
Last synced: about 1 year ago
JSON representation
Type level helper to ensure type safety in Vuex
- Host: GitHub
- URL: https://github.com/ktsn/vuex-type-helper
- Owner: ktsn
- Created: 2017-08-26T03:49:36.000Z (almost 9 years ago)
- Default Branch: master
- Last Pushed: 2020-12-14T06:29:56.000Z (over 5 years ago)
- Last Synced: 2025-03-26T08:11:19.667Z (about 1 year ago)
- Topics: type, type-safety, typescript, vue, vuex
- Language: TypeScript
- Homepage:
- Size: 18.6 KB
- Stars: 104
- Watchers: 4
- Forks: 11
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Vuex Type Helper
Type level helper to ensure type safety in Vuex.
## Installation
```bash
# npm
$ npm install vuex-type-helper
# yarn
$ yarn add vuex-type-helper
```
## Example
```ts
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
}
reset: void // having no payload
}
export interface CounterActions {
// actionName: actionPayloadType
incAsync: {
amount: number
delay: number
}
reset: void // having no payload
}
/**
* Implement the module
*/
const state: CounterState = {
count: 0
}
const getters: DefineGetters = {
half: state => state.count / 2
}
const mutations: DefineMutations = {
inc (state, { amount }) {
state.count += amount
},
reset(state) {
state.count = 0
}
}
const actions: DefineActions = {
incAsync ({ commit }, payload) {
setTimeout(() => {
commit('inc', payload)
}, payload.delay)
},
reset({ commit }) {
commit('reset')
}
}
/**
* 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>({
type: 'incAsync',
amount: 1,
delay: 1000
})
store.dispatch>({
type: 'reset'
})
store.commit>({
type: 'inc',
amount: 1
})
store.commit>({
type: 'reset'
})
```
## License
MIT