簡體   English   中英

減少()到 state object Typescript

[英]Reduce() to state object Typescript

我在.ts文件中使用Array.prototype.reduce() function 訪問 redux state 時遇到問題。

這是簡化的示例:

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 中非常困難(我的意思是非常手動):

// 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;
}

基本上,您聲明的 function 過載與 state 中的級別一樣多。 不過,您得到的回報是非常甜蜜的,看看這個TypeScript 操場的代碼和示例!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM