簡體   English   中英

對象在打字稿中可能是“空”

[英]object is possibly 'null' in typescript

 interface IRoleAddProps { roles: Array<IRole> } interface IRoleAddState { current: IRole | null } class RoleAdd extends React.Component<IRoleAddProps, IRoleAddState> { state = { current: null, } renderNoneSelect = () => { return ( <div styleName="empty"> <SvgIcon name="arrow" styleName="icon-arrow" /> <span>Empty</span> </div> ) } onRoleClick = (role: IRole) => { this.setState({ current: role, }) } render() { const { roles } = this.props const current = this.state.current return ( <div styleName="role-add"> <div styleName="role-list"> <div styleName="title">Select role:</div> <div styleName="list"> {roles.map(role => { const cls = classNames({ item: true, active: current && ( current.id === role.id ) }) return ( <div key={role.id} styleName={cls} className="g-text-inline" onClick={this.onRoleClick.bind(this, role)} > <CheckBox /> <span>{role.name}</span> </div> ) })} </div> </div> <div styleName="view"> {!current && this.renderNoneSelect()} {current && 'view'} </div> </div> ) } } export default RoleAdd 

這樣的代碼,但TS仍然告訴我:

在此輸入圖像描述

甚至我試過:

在此輸入圖像描述

並且“!” 也行不通

在此輸入圖像描述

正如您所看到的,“當前”對象不能為null,因為我在使用它之前進行了空檢查。

但打字稿引擎仍然顯示我的錯誤。

我想知道是因為我用null值初始化了當前對象,但是ts無法從setState中找出類型,所以它需要當前的null嗎?

在構造函數中明確定義狀態應該可以解決問題。

constructor(props) {
    super(props);

    this.state = {
        current: null;
    }
}

您需要為state分配類型,例如

state: IRoleAddState = {
    current: null
};

然后,state將是IRoleAddState類型而不是{ current: null } 之后,您嘗試的方法將起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM