代码之家  ›  专栏  ›  技术社区  ›  JD.

流-可能类型与看似有效的默认对象参数不兼容

  •  1
  • JD.  · 技术社区  · 6 年前

    考虑代码:

    // @flow
    type Params = {
      value: ?number,
    }
    function acceptsMaybeNumber({
    
      // Error:(6, 3) null or undefined [1] is incompatible with number [2].
      // value = 4 // <--- DOESN'T WORK
    
      // Error:(7, 3) null or undefined [1] is incompatible with number [2].
      // Error:(7, 11) null [1] is incompatible with number [2].
      // value = null // <--- DOESN'T WORK
    
      // Error:(15, 3) null or undefined [1] is incompatible with number [2].
      // Error:(16, 11) undefined [1] is incompatible with number [2].
      // value = undefined // <--- DOESN'T WORK
    
      value // <-- WORKS
    }: Params) {
      console.log(value);
    }
    

    value 输入 Params 类型接受 number ,则, null undefined 类型,将此键的默认值设置为 应该 有效,但会抛出以下错误。

    为什么会发生这种情况?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Dave Meehan    6 年前

    正如@TLadd所指出的,它似乎是 bug

    问题具体在于使用 null 在使用默认值进行对象分解时作为允许的类型。

    $FlowFixMe 可以用来抑制错误,避免损坏代码,或者可以 create your own suppression e、 g。 $FlowDestructuringDefaultBug 。注意:您需要将$Flow suppression注释放在紧靠默认赋值之前的一行上,因此您需要像在原始示例中那样跨多行打断参数。

    以下是一些可能适合您的用例的替代方案( Try ):

    // @flow
    type MaybeParams = {
      value: ?number,
    }
    function acceptsMaybeNumber({
      // originalValue = 1  // FAIL
      // $FlowFixMe
      value = 1,            // PASS (but not in Try where $FlowFixMe is disabled)
    }: MaybeParams) {
      console.log(value);
    }
    
    type OptionalParams = {
      value?: number,
    }
    function acceptsOptionalNumber({
      value = 1,                // PASS
    }: OptionalParams) {
      console.log(value);
    }
    
    acceptsOptionalNumber({ })  // PASS
    
    
    type UndefinedParams = {
      value: void | number,
    }
    function acceptsUndefinedNumber({
      value = 1,                // PASS
    }: UndefinedParams) {
      console.log(value);
    }
    
    acceptsUndefinedNumber({ value: undefined })    // PASS
    

    如果您特别希望将null作为一个允许的、指定的值来处理,那么您必须避免在解构中指定默认值。

        2
  •  2
  •   TLadd    6 年前

    这是流程中的一个bug。 https://github.com/facebook/flow/issues/183#issuecomment-358607052 。最简单的修复方法可能就是不依赖默认的解构值。比如说

    type Params = {
      value?: ?number,
    }
    function acceptsMaybeNumber(params: Params) {
      const value = typeof params.value === 'number' ? params.value : 4
      console.log(value);
    }