typescript - 如何为 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 {}
有没有更好的方法来表达类型?
解决方案
您可以将类型作为泛型提供给mapState
方法,如下所示:
@Component({
computed: {
...mapState<MyModel>( MY_NAMESPACE, {
fooIndex: (state: MyModel) => state.values.indexOf('foo')
}),
}
})
export default class MyComponent extends Vue {}
推荐阅读
- database - 删除 id 但保留 Peewee db 中的数据
- react-native - react-native 运行 android 构建失败
- swift - Adobe PDF 链接不会在运行 IOS 13.o、13.1.2 和 13.2 beta 的已编译 Swift 5 中打开,但在所有 IOS 版本 < 13.0 中打开
- architecture - 关于 2 级页表操作的问题
- javascript - 在 Beautifulsoup 中运行 JavaScript
- swift - Xcode 11 & iOS13,使用 UIKIT 不能改变 UIViewController 的背景颜色
- c# - Asp.net 核心 Web API:更改默认编码。我如何接受越南语字符作为动作参数?
- angular - IONIC 4 项目在构建后不会加载
- javascript - 如何检测 chrome devtools 中的 CPU 使用率过高
- arduino - Arduino RFID 激活的防自行车盗窃系统的编码帮助