避免可能未定义的值

时间:2017-08-16 06:58:13

标签: flowtype flow-typed

在流程中,我有很多可选参数,例如:

type Props = {
   assets?: string[]
}

当我确定它们没有未定义时,我只访问这些,但Flow会警告“属性无法访问可能未定义的值”。

但是我知道它是定义的,因为我只在定义它时才调用它。例如:

class MyComponent扩展了React.Component {    filterAssets(){        return this.props.assets.filter(....);    }    render(){        返回this.props.assets? filterAssets():null    } }

看到我已经有了if语句。反正是为了避免这个警告,而没有添加真正的javascript逻辑只是为了隐藏这个警告?

通过真正的js逻辑,我的意思是在我想要避免的方法中:

filterAssets(){        if(!this.props.assets)返回; //添加此行        return this.props.assets.filter(....);    }

1 个答案:

答案 0 :(得分:1)

您必须在filterAssets内进行细化。否则,可能会从应用程序的其他位置不安全地调用该函数。

class MyComponent extends React.Component { 
  props: {
    assets?: string[]
  }

  filterAssets() { 
    return this.props.assets 
      ? this.props.assets.filter(....) : null; 
  } 

  render() { 
    return this.filterAssets();
  } 
}

或者,您可以重构filterAssets以获取明确键入的assets属性:

class MyComponent extends React.Component { 
  props: {
    assets?: string[]
  }

  filterAssets(assets: string[]) { return assets.filter(....); } 

  render() { 
    const assets = this.props.assets;
    return assets ? this.filterAssets(assets) : null 
  } 
}