首页 文章

为什么Flow无法使用字符串鉴别器通过我的操作类型进行优化?

提问于
浏览
0

我正在使用Flow在Redux应用程序中编写Reducer . 我的reducer操作需要两种操作, NumberActionStringAction .

NumberAction 具有 numberValue 属性,而 StringAction 具有 stringValue 属性 . 并且,作为Redux操作,它们都具有 type 属性,分别为 NUMBER_ACTIONSTRING_ACTION . 我测试 action.type 以确定 switch 语句中正在处理的操作类型 .

我理解the documentation的方式,这应该足以让Flow确定 action 的类型 . 但是,当我尝试访问给定操作类型中不存在的属性时,它不会给我一个错误 . 完整代码:

// @flow
export type NumberAction = {|
    type : 'NUMBER_ACTION',
    numberValue : number
|}

export type StringAction = {|
    type : 'STRING_ACTION',
    stringValue : string
|}

type Action = | NumberAction | StringAction;

export default function my(action : Action) {
    switch (action.type) {
        case 'NUMBER_ACTION' : {
            let value : number = action.numberValue;
            console.log("value = ", value);
            break;
        }
        case 'STRING_VALUE' : {
            let value : number = action.numberValue; // This should error, because StringAction doesn't have a numberValue property
            console.log("value = ", value);
            break;
        }
    }
}

当我在 STRING_VALUE 案例中尝试访问 action.numberValue 时,为什么我没有收到错误?

但是,如果我使用整数作为操作标识符,我会得到预期的错误:

// @flow
export type NumberAction = {|
    type : 1, // Note: number
    numberValue : number
|}

export type StringAction = {|
    type : 2, // Note: number
    stringValue : string
|}

type Action = | NumberAction | StringAction;

export default function my(action : Action) {
    switch (action.type) {
        case 1 : {
            let value : number = action.numberValue;
            console.log("value = ", value);
            break;
        }
        case 2 : {
            let value : number = action.numberValue; // This errors: Flow: property `numberValue`. Property not found in object type. 
            console.log("value = ", value);
            break;
        }
    }
}

我不应该这样使用字符串作为类型鉴别器吗?

1 回答

  • 0

    这似乎是Flow 0.48.0中的一个错误 .

    更新到Flow 0.49.1时,问题就消失了 .

相关问题