[英]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.