Javascript Reduce()到state对象类型脚本

Javascript Reduce()到state对象类型脚本,javascript,typescript,redux,Javascript,Typescript,Redux,使用.ts文件中的Array.prototype.reduce()函数访问redux状态时遇到问题 以下是简化的示例: const state = store.getState(); const path: string = ["orders", "delay"].reduce( (accumulator, currentValue) => accumulator[currentValue], state) // it correlates

使用
.ts
文件中的
Array.prototype.reduce()
函数访问redux状态时遇到问题

以下是简化的示例:

const state = store.getState();
const path: string = ["orders", "delay"].reduce(
   (accumulator, currentValue) => accumulator[currentValue], state) 

// it correlates to: const path = state.orders.delay 

// accumulator - string
// currentValue - string
// state - result of combineReducers, middleware, and devtools 
在reduce()的末尾,我将得到一个“字符串”,但现在我得到一个错误,因为state不是“字符串”类型

如何正确键入?

在TypeScript中,这是非常困难的(我指的是非常手动的):

//不幸的是,您需要编写大量手动函数重载
函数getValue(状态:S,路径:[P1]):S[P1];
函数getValue(状态:S,路径:[P1,P2]):S[P1][P2];
函数getValue(
国家:S,
路径:[P1、P2、P3],
):S[P1][P2][P3];
函数getValue(状态:S,路径:(keyof S)[]){
//您还可以使用reduce解决方案,因为它不涉及函数调用,所以速度更快
让电流:任意=状态;
对于(设i=0;i

基本上,您声明的函数重载与状态中的级别一样多。然而,您得到的回报是非常甜蜜的,请通过代码和示例来检查这一点

对于任意深度的输入来说,这将是非常尴尬的。我建议使用递归。嘿,Aluan,你能提供一个例子吗?Ján,我不知道数组中有多少项,它可能是1或100(只是一个例子),我可以简单地添加
any
const state:any=store.getState()
,它会对它进行脏修复,但如果有任何合理的类型检查选项,我宁愿不这样做。哦,是的,抱歉,我的解决方案只解决了整个问题的返回类型,并且类型检查了路径。我想我脑子里有一个很好的解决方案,让我回到我的笔记本电脑上试试。但是它需要TypeScript 4.0,这是你可以接受的吗?我可以将它更新到最新版本,但是我可以看到最新的稳定版本3.9.5…如果它有帮助,下面是