【问题标题】:How can I supply types to Vuex mapState functions?如何为 Vuex mapState 函数提供类型?
【发布时间】:2020-06-16 00:54:56
【问题描述】:

我在我的 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 {}

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

【问题讨论】:

标签: typescript vue.js vuex


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-08-17
    • 2020-05-22
    • 2019-09-25
    • 2019-01-03
    • 2021-12-01
    • 2021-03-05
    • 2018-11-04
    • 2017-12-06
    • 2022-11-19
    相关资源
    最近更新 更多