首页 > 解决方案 > 如何为 Vuex mapState 函数提供类型?

问题描述

我在我的 Vuex 组件中使用 Typescript,并希望为mapState. 直觉上,我是这样写的:

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

这在过去有效,但是在升级我的依赖项后,这不再有效,我收到错误No overload matches this call. Overload 1 of 6, '(namespace: string, map: string[]): { [x: string]: Computed; }', gave the following error.

作为一种解决方法,我可以从函数参数中删除类型并像这样进行转换:

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

有没有更好的方法来表达类型?

标签: typescriptvue.jsvuex

解决方案


您可以将类型作为泛型提供给mapState方法,如下所示:

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

推荐阅读