首页 > 解决方案 > 字符串与数字不兼容(默认为流类型可选属性)

问题描述

给定以下伪 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]

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

标签: javascriptreactjsecmascript-6flowtypedestructuring

解决方案


Flow 中有一个已知错误,当​​函数具有类型为联合的参数的默认参数时,会导致报告错误的类型错误。

您可以像这样解决它:

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

Component.defaultProps = {
    width: '100%',
}

推荐阅读