【问题标题】:refining flow union type精炼流动联合式
【发布时间】:2017-10-01 08:07:08
【问题描述】:

请看下面的代码。我必须进行两次强制转换以避免任何流量错误。如果我改用注释掉的行,它会抱怨。

playground

/* @flow */

import * as React from "react";

type ConfObj = { label: string };
type Conf = React.Node | ConfObj;
type MyComponentProp = {
    confs: Array<Conf>,
}

export default function MyComponent({
  confs = [],
}: MyComponentProp) {
  const items = confs.map((item, idx) => {
    if (React.isValidElement(item)) {
      // return React.cloneElement(item, {
      return React.cloneElement(((item: any): React.Element<*>), {
        key: idx.toString(),
      });
    }

   const item2 = ((item: any): ConfObj);
   return <span>{item2.label}</span>;
   // return <span>{item.label}</span>;
  });

  return <div>items</div>
}

有没有更好的方法来避免强制转换。有没有更好的方法来写isValidElement,这样一旦if条件匹配,flow就可以推断出类型。例如,如果它是一个有效的反应元素,我为什么需要强制转换它?或者如果不是,为什么访问label 会出错?

【问题讨论】:

    标签: javascript reactjs flowtype


    【解决方案1】:

    item 的类型为 Conf(即 Node | ConfObj) 当您输入if 语句时,flow 不确定item 是否是有效的Element&lt;*&gt;(我认为这可能被flow 知道),因此您必须明确地对其进行类型转换。

    &lt;span&gt;{item.label}&lt;/span&gt; 也有同样的问题。您还必须将其显式类型转换为ConfObj,因为Node 没有label 属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-10
      • 1970-01-01
      • 2019-02-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多