How can I supply types to Vuex mapState functions?
Asked Answered
B

1

6

I'm using Typescript in my Vuex component and would like to provide types to the mapping functions in mapState. Intuitively, I wrote it like this:

@Component({
  computed: {
    ...mapState( MY_NAMESPACE, {
      fooIndex: ( state: MyModel ) => state.values.indexOf('foo')
    })
    // more computed props here
  }
})
export default class MyComponent extends Vue {}

This has worked in the past, however after an upgrade of my dependencies this does not work any more, I'm getting the error No overload matches this call. Overload 1 of 6, '(namespace: string, map: string[]): { [x: string]: Computed; }', gave the following error.

As a workaround I can remove the type from the function parameter and cast like this:

@Component({
  computed: {
    ...mapState( MY_NAMESPACE, {
      fooIndex: state => (state as MyModel).values.indexOf('foo')
    }),
  }
})
export default class MyComponent extends Vue {}

Is there any better way to express the types?

Berar answered 3/3, 2020 at 15:36 Comment(2)
You are using Class style component. Would vuex-class help?Rugged
Did you resolve this? I'm experiencing the same issue.Schismatic
I
0

You can provide the type as a generic to the mapState method, like so:

@Component({
  computed: {
    ...mapState<MyModel>( MY_NAMESPACE, {
      fooIndex: (state: MyModel) => state.values.indexOf('foo')
    }),
  }
})
export default class MyComponent extends Vue {}
Irremovable answered 16/1, 2022 at 9:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.