2017-04-05 45 views
0

我正在嘗試使用Flow不交疊聯合來強制鍵入Redux操作對象,如Flow文檔(https://flow.org/en/docs/frameworks/redux/)中所建議的,但我現在遇到流拋出問題處理默認redux操作的錯誤(@@redux/INIT@@redux/PROBE_UNKNOWN_ACTION等)。Flow + Redux:Error與Redux默認操作和強類型操作

這段代碼的樣本是:

// Constant action type strings 
export const INIT_STORIES: 'INIT_STORIES' = 'INIT_STORIES'; 
export const UPDATE_STORY: 'UPDATE_STORY' = 'UPDATE_STORY'; 

// Strongly typed action objects 
export type InitAction = { 
    type: typeof INIT_STORIES, stories: Array<Story> 
}; 
export type UpdateAction = { 
    type: typeof UPDATE_STORY, storyIndex: number, story: Story 
}; 

// Disjoint union wrapper 
export type ActionType = 
| InitAction 
| UpdateAction; 

//reducer 
export default function storiesReducer(
    stories: Array<Story> = [], 
    action: ActionType 
): Array<Story> { 
    // Error is thrown at function invocation, prior to the first inner line of function 
    // Uncaught TypeError: [tcomb] Invalid value {"type": "@@redux/INIT" 
    console.log(action); 
    ... 
} 

我只能夠找到1個問題/解決方案在線這個問題,它採用了更復雜的流運行時來解決這個問題。 (https://github.com/codemix/flow-runtime/issues/80

我覺得像Redux與Flow的集成推薦的語法,應該有一個更簡單的解決方案比?我試圖使函數參數action的類型與具有未定義字符串類型的對象(即{ type: string })進行不相交聯合,但是在縮減器中引發了靜態linting/typing類型錯誤,因爲它無法確定不相交的分支聯合對象action對象是。

+0

您是否使用流式輸入提供的libdef? –

+0

@LewisChung不,我不知道,有沒有現成的圖書館。我一定會考慮這一點。我想我可以將我的動作定義應用於'flow-typed' libdef中的基本redux動作類型的頂點上的不相交聯合? – Mike

+0

由於您使用的是tcomb,因此您仍然會遇到同樣的問題。我問你是否使用了流式輸入,因爲它看起來可以修改這裏存在的流類型定義:https://github.com/flowtype/flow-typed/blob/master/definitions/npm/redux_v3.xx /flow_v0.33.x-/redux_v3.xxjs自動解釋默認流程操作,因此您不會得到{「type」:「@@ redux/INIT」}。這就是說,我不太清楚tcomb實際上是如何使用流類型的libdefs。 –

回答

0

最簡單的解決方案,而無需輸入完整的flow-typed包終極版,是一個不相交併{ type: $Subtype<string> }添加到ActionType不交類型,如下:

// Disjoint union wrapper 
export type ActionType = 
| InitAction 
| UpdateAction 
| { type: $Subtype<string> }; 


//reducer 
export default function storiesReducer(
    stories: Array<Story> = [], 
    action: ActionType 
): Array<Story> { 
    console.log(action); 
    ... 
} 

雖然這不會引發相應的錯誤,如果動作類型字符串輸入錯誤,因爲它允許所有字符串類型,它將允許適當的分支來識別開關/大小寫塊內的不同對象形狀。