Noitidart
Noitidart

Reputation: 37238

Avoid possibly undefined value

In flow I have optional parameters a lot, like this:

type Props = {
   assets?: string[]
}

I only access these when I know for sure they are not undefined, however Flow keeps warning about "Property cannot be access on possibly undefined value".

However I know it is defined for sure, because I only call this method when it is defined. For instance like this:

class MyComponent extends React.Component { filterAssets() { return this.props.assets.filter(....); } render() { return this.props.assets ? filterAssets() : null } }

See I have a if statement there already. Is there anyway to avoid this warning, without adding real javascript logic just to hide this warning?

By real js logic I mean like in the method I want to avoid:

filterAssets() { if (!this.props.assets) return; // adding this line return this.props.assets.filter(....); }

Upvotes: 0

Views: 267

Answers (1)

Ross Solomon
Ross Solomon

Reputation: 665

You must do the refinement within filterAssets. Otherwise, that function could unsafely be called from elsewhere in the app.

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

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

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

Alternately, you could refactor filterAssets to take a definitely typed assets property:

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 
  } 
}

Upvotes: 1

Related Questions