首页 > 解决方案 > 流不相交联合检查适用于文字字符串,但不适用于常量

问题描述

我正在尝试使用 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;
    }
};

标签: flowtype

解决方案


推荐阅读