How can I supply types to Vuex mapState functions?

Viewed 982

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?

1 Answers

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 {}
Related