流程抱怨对象默认值解构中的类型不兼容

Fez*_*sta 5 javascript flowtype

我要使用Flow验证这个非常简单的功能:

// @flow
type Props = {
  width: string | number,
};

function fun({
  width = '30em',
}: Props) {
  return width;
}
Run Code Online (Sandbox Code Playgroud)

问题是我收到此错误:

8:   width = '30em',
     ^ number. This type is incompatible with
8:   width = '30em',
     ^ string
8:   width = '30em',
     ^ string. This type is incompatible with
8:   width = '30em',
     ^ number
8:   width = '30em',
             ^ string. This type is incompatible with
8:   width = '30em',
     ^ number
Run Code Online (Sandbox Code Playgroud)

我想知道我做错了什么...这种其他方式可以正常工作:

// @flow
type Props = {
  width: string | number,
};

function fun(props: Props) {
  const {
    width = '30em',
  } = props;
  return width;
}
Run Code Online (Sandbox Code Playgroud)

而且似乎支持函数参数中的此语法,因为:

// @flow
type Props = {
  width: string,
};

function fun({ width = '30em' }: Props) {
  return width;
}
Run Code Online (Sandbox Code Playgroud)

这样很好。

有想法吗?

the*_*kes 0

Flow 不支持解构默认分配。

您应该单独定义 defaultProps,然后使用它们作为默认值,而不是同时分配默认值和解构。

例如:

type Props = {
    width: string | number
}

const defaultProps: Props = {
    width: '30em',
}

function fun ({ width }: Props = defaultProps) {
  return width
}

fun({ width: 30 })   // => 30
fun({ width: '30' }) // => '30'
fun()                // => '30em'

fun({ width: true }) // $ExpectError
Run Code Online (Sandbox Code Playgroud)

这是一个工作示例