diff --git a/src/bindings.ts b/src/bindings.ts index f0c9231..03bb3d2 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -9,7 +9,7 @@ import { export type VuexDecorator = (proto: V, key: string) => void -export type StateTransformer = (state: any, getters: any) => any +export type StateTransformer = (state: S, getters: G) => any export type MapHelper = typeof mapState | typeof mapGetters | typeof mapActions | typeof mapMutations @@ -23,18 +23,18 @@ export interface BindingHelper { (type: string, options?: BindingOptions): VuexDecorator } -export interface StateBindingHelper extends BindingHelper { - (type: StateTransformer, options?: BindingOptions): VuexDecorator +export interface StateBindingHelper extends BindingHelper { + (type: StateTransformer, options?: BindingOptions): VuexDecorator } -export interface BindingHelpers { - State: StateBindingHelper +export interface BindingHelpers { + State: StateBindingHelper Getter: BindingHelper Mutation: BindingHelper Action: BindingHelper } -export const State = createBindingHelper('computed', mapState) as StateBindingHelper +export const State = createBindingHelper('computed', mapState) as StateBindingHelper export const Getter = createBindingHelper('computed', mapGetters) @@ -42,7 +42,11 @@ export const Action = createBindingHelper('methods', mapActions) export const Mutation = createBindingHelper('methods', mapMutations) -export function namespace (namespace: string): BindingHelpers +export function namespace>( + namespace: string +): H extends BindingHelpers + ? BindingHelpers + : BindingHelpers export function namespace ( namespace: string, helper: T diff --git a/test/bindings.ts b/test/bindings.ts index 57c7085..42aa65b 100644 --- a/test/bindings.ts +++ b/test/bindings.ts @@ -8,7 +8,8 @@ import { Getter, Action, Mutation, - namespace + namespace, + BindingHelpers } from '../src/bindings' Vue.config.productionTip = false @@ -62,28 +63,48 @@ describe('binding helpers', () => { }) it('State: namespace', () => { + type ComplexNumber = { + real: number + imaginary: number + } + + type FooState = ComplexNumber + const store = new Vuex.Store({ modules: { foo: { namespaced: true, - state: { value: 1 } + state: { + real: 1, + imaginary: 2 + } as FooState } } }) - const foo = namespace('foo') + const foo = namespace>('foo') @Component class MyComp extends Vue { - @foo.State('value') + @foo.State('real') bar: number - @foo.State value: number + @foo.State real: number + + @foo.State((state) => { + return { + real: -state.real, + imaginary: -state.imaginary + } + }) + negative: ComplexNumber } const c = new MyComp({ store }) assert(c.bar === 1) - assert(c.value === 1) + assert(c.real === 1) + assert(c.negative.real === -1) + assert(c.negative.imaginary === -2) }) it('Getter: type', () => {