简体   繁体   English

减少()到 state object Typescript

[英]Reduce() to state object Typescript

I'm having a trouble accessing redux state with Array.prototype.reduce() function inside a .ts file.我在.ts文件中使用Array.prototype.reduce() function 访问 redux state 时遇到问题。

Here is the simplified example:这是简化的示例:

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 

In the end of the reduce() I'll get a "string", but now I'm getting an error because state is not a "string" type.在 reduce() 结束时,我会得到一个“字符串”,但现在我收到一个错误,因为 state 不是“字符串”类型。

How do I type this correctly?如何正确输入?

This is very difficult (by which I mean very manual) in TypeScript:这在 TypeScript 中非常困难(我的意思是非常手动):

// Unfortunately you will need to write a lot of manual function overloads
function getValue<S, P1 extends keyof S>(state: S, path: [P1]): S[P1];
function getValue<S, P1 extends keyof S, P2 extends keyof S[P1]>(state: S, path: [P1, P2]): S[P1][P2];
function getValue<S, P1 extends keyof S, P2 extends keyof S[P1], P3 extends keyof S[P1][P2]>(
  state: S,
  path: [P1, P2, P3],
): S[P1][P2][P3];
function getValue<S>(state: S, path: (keyof S)[]) {
  // You can also use your reduce solution, this is faster since it does not involve a function call
  let current: any = state;
  for (let i = 0; i < path.length; i++) current = current[path[i]];

  return current;
}

Basically you are declaring as many function overloads as there are levels in your state.基本上,您声明的 function 过载与 state 中的级别一样多。 What you get in return is pretty sweet though, check out this TypeScript playground with the code and examples!不过,您得到的回报是非常甜蜜的,看看这个TypeScript 操场的代码和示例!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM