避免可能未定义值

问题描述:

在流我有可选参数很多,如:避免可能未定义值

type Props = { 
    assets?: string[] 
} 

我只访问这些的时候我肯定知道他们是不是不确定的,但是流量不断警告有关“属性不能被访问在可能未定义的价值“。

但是我知道这是肯定的定义,因为我只在定义时调用此方法。比如像这样:

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

请参阅我已经有一个if语句。无论如何避免这个警告,没有添加真正的JavaScript逻辑只是为了隐藏这个警告?

通过真正的JS逻辑我的意思是一样的方法,我想避免:(!this.props.assets)

filterAssets(){ 如果回报; //添加此行 return this.props.assets.filter(....); }

您必须在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 
    } 
} 
+1

喔“不安全从其他地方称为”这是一个很好的点。我也喜欢你的绝对类型的想法。感谢2个解决方案! – Noitidart

+1

乐意帮忙! :) –

+0

是否有任何其他方式表明资产是肯定输入的流? – Noitidart