Last active
July 24, 2017 16:26
-
-
Save ktsn/191695475d356b7a12999d07f2b5e07d to your computer and use it in GitHub Desktop.
Discovering type safe usage of Vuex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Store, ActionContext } from 'vuex' | |
type Actions<S, P> = { | |
[K in keyof P]: (ctx: ActionContext<S, any>, payload: P[K]) => void | Promise<any> | |
} | |
type Mutations<S, P> = { | |
[K in keyof P]: (state: S, payload: P[K]) => void | |
} | |
type Mapper<P> = { | |
[K in keyof P]: { type: K } & P[K] | |
} | |
type Dispatch<P, M extends Mapper<P> = Mapper<P>, K extends keyof M = keyof M> = M[K] | |
interface MutationPayloads { | |
foo: { | |
value: number | |
} | |
bar: { | |
value: string | |
} | |
} | |
const state = { | |
count: 0 | |
} | |
const mutations: Mutations<typeof state, MutationPayloads> = { | |
foo(state, payload) { | |
const n: number = payload.value | |
}, | |
bar(state, payload) { | |
const s: string = payload.value | |
} | |
} | |
const example = { state, mutations } | |
const store = new Store({ | |
modules: { | |
example | |
} | |
}) | |
store.commit<Dispatch<MutationPayloads>>({ | |
type: 'bar', | |
value: 'hello' | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment