【问题标题】:Flow complaining about incompatible type in object default values destructuring流抱怨对象默认值解构中的类型不兼容
【发布时间】:2017-12-03 08:33:53
【问题描述】:

我有一个非常简单的函数,我正在尝试使用 Flow 进行验证:

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

function fun({
  width = '30em',
}: Props) {
  return width;
}

问题是我得到了这个错误:

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

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

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

function fun(props: Props) {
  const {
    width = '30em',
  } = props;
  return width;
}

函数参数中的这种语法似乎得到了支持,因为:

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

function fun({ width = '30em' }: Props) {
  return width;
}

这很好用。

想法?

【问题讨论】:

  • 如果这是问题所在,即使在我的第二个示例中它也应该抛出错误。此外,它应该引发语法错误。此外,它适用于单一类型。
  • 这绝对看起来像一个错误。如果您认为它与 Jared 链接的不一样,请登录另一个。
  • 我已经做到了here

标签: javascript flowtype


【解决方案1】:

Destructuring default assignment is not supported in 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

这是working example

【讨论】:

  • 我的是一个函数。不是 React 组件
  • 是的,我意识到了这一点。我不确定你的观点。您在类型定义中使用“type = Props”,所以我定义了一个 const“defaultProps”。请提供有关否决票的更多解释,因为这是解决您问题的有效解决方案。
  • 如果您的目标是使用解构默认分配,据我所知,这在流程中不受支持。 github.com/facebook/flow/issues/881
  • 您只是在重复我的问题和 cmets 中提到的内容。这就是重点。
  • 现在支持解构默认分配,因为我的第二个示例运行良好。我的第三个示例是您的“解决方案”的一个简单变体。你怎么能说你没有重复现有的信息?您提供的 URL 已在 cmets 中。
【解决方案2】:

您可以尝试输入整个函数而不是专门输入 Props:

const fun: (Props) => string | number = ({
  width = '30em',
}) => {
  return width;
}

您所观察到的问题已经存在很长一段时间了。见issue 2198

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    相关资源
    最近更新 更多