flowtype - 流不相交联合检查适用于文字字符串,但不适用于常量
问题描述
我正在尝试使用 Flow 正确键入 redux 动作,但在使用动作类型的常量时,它没有正确检查不相交的类型。
我在很多地方都读到这是正确的方法,但我无法让DOUBLE
常量出错(所以这并不是真正正确地输入 switch 语句)。
还有另一种方法可以做到这一点吗?
// @flow
export const INCREMENT: 'INCREMENT' = 'INCREMENT';
export type IncrementAction = {|
type: typeof INCREMENT,
|};
export const DECREMENT: 'DECREMENT' = 'DECREMENT';
export type DecrementAction = {|
type: typeof DECREMENT,
|};
export const DOUBLE: 'DOUBLE' = 'DOUBLE';
export type DoubleAction = {|
type: typeof DOUBLE,
|};
// Notice I didn't include DoubleAction
export type Action = IncrementAction | DecrementAction;
type State = {|
counter: number,
|};
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case INCREMENT:
return { counter: state.counter + 1 };
case DECREMENT:
return { counter: state.counter - 1 };
// This case should fail because it's in none of the actions in the disjoint union
case DOUBLE:
return { counter: state.counter * 2 };
// This case does fail because it's a literal instead of a constants
case 'TRIPLE':
return { counter: state.counter * 3 };
default:
return state;
}
};
解决方案
推荐阅读
- java - 如何接收短信?
- javascript - 从迭代器中获取当前值
- javascript - 从异步函数渲染反应本机孩子
- php - MySQL从一列计算整数值的总和并将结果存储在另一个表中
- java - 如何在 ROOTED 设备上录制 VOIP 通话?
- javascript - 如何在 php mysql 查询中获取 javascript 变量?
- android - 有没有办法检测安装的应用程序是否正在使用?
- wordpress - WordPress。如何在 if else 语句中使用简码?
- c++ - 是否可以在单元测试中使用 QCustomPlot?
- java - 如何在 JSON for 循环中设置 onClick 侦听器以检索单击的项目或文本?