【问题标题】:Disjoint unions with undefined tag带有未定义标签的不相交联合
【发布时间】:2016-12-23 20:45:07
【问题描述】:

我使用的 JSON 数据模型是由分支节点和特殊节点组成的嵌套结构,这些节点根据 $type 键的存在来消除歧义,例如:

{ "a": { "b": { "$type": "special" } } }

我想使用 Flow 对此进行建模,但标记的联合似乎要求不同的标记具有相同的类型,例如:

// @flow
type Special = { $type: 'special'};
type Branch = { $type: ?null, [key:string]: any };

function isSpecial(param: Special | Branch): ?Special {
    if (param.$type === 'special') {
        return param;
    }
}

给出以下错误:

$ node_modules/.bin/flow check-contents < example.js 
-:2
2: type Special = { $type: 'special'};
                            ^^^^^^^^^ string literal `special`. This type is incompatible with
3: type NotSpecial = { $type: ?null, [key:string]: any };
                                ^^^^ null

-:3
3: type NotSpecial = { $type: ?null, [key:string]: any };
                                ^^^^ null. This type is incompatible with
2: type Special = { $type: 'special'};
                            ^^^^^^^^^ string literal `special`

-:3
3: type NotSpecial = { $type: ?null, [key:string]: any };
                                ^^^^ undefined. This type is incompatible with
2: type Special = { $type: 'special'};
                            ^^^^^^^^^ string literal `special`


Found 3 errors

有没有办法处理这样的情况?

【问题讨论】:

    标签: flowtype


    【解决方案1】:

    虽然理论上这应该可行,但 Flow 不支持。 Flow 要求标签具有相同的类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      • 2014-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多