【问题标题】:String is incompatible with number (Flow typing optional property with default)字符串与数字不兼容(默认为流类型可选属性)
【发布时间】:2019-02-23 19:31:17
【问题描述】:

给定以下伪 React 组件:

type Props = {
  width?: number | string
};

const Component = ({
  width = '100%'
}: Props) => ( /* component body */ )

Flow 抛出以下错误:

6:   width = '100%'
     ^ string [1] is incompatible with number [2].
   References:
   2:   width?: number | string
                         ^ [1]
   2:   width?: number | string
                ^ [2]

6:   width = '100%'
             ^ string [1] is incompatible with number [2].
   References:
   6:   width = '100%'
                ^ [1]
   2:   width?: number | string
                ^ [2]

组件应接受width 的3 种可能类型:void | number | string。有正确的输入方法吗?我可以通过删除 '100%' 的默认值来修复该错误,但该解决方案不太惯用。

【问题讨论】:

    标签: javascript reactjs ecmascript-6 flowtype destructuring


    【解决方案1】:

    有一个known bug in Flow,当函数有一个类型为联合的参数的默认参数时,会导致报告错误的类型错误。

    你可以这样解决它:

    const Component = ({ width }: Props) => ( /* component body */ )
    
    Component.defaultProps = {
        width: '100%',
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-22
      • 1970-01-01
      • 1970-01-01
      • 2018-08-27
      • 1970-01-01
      相关资源
      最近更新 更多