【问题标题】:object is possibly 'null' in typescript打字稿中的对象可能是“空”
【发布时间】:2019-01-24 10:08:52
【问题描述】:

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 值初始化了当前对象,但是 ts 无法从 setState 中找出类型,所以它总是将 current 设为 null?

【问题讨论】:

  • 它不起作用,因为state 成员在派生类中被覆盖,并且它获得了所提供初始值的推断类型

标签: javascript reactjs typescript


【解决方案1】:

您需要为state 分配一个类型,例如

state: IRoleAddState = {
    current: null
};

然后,状态将是 IRoleAddState 类型,而不是 { current: null }。之后,您尝试的方法将起作用。

【讨论】:

    【解决方案2】:

    在构造函数中明确定义状态应该可以解决问题。

    constructor(props) {
        super(props);
    
        this.state = {
            current: null;
        }
    }
    
    

    【讨论】:

      猜你喜欢
      • 2017-10-12
      • 2022-01-26
      • 2021-09-27
      • 2021-12-01
      • 1970-01-01
      • 2020-11-07
      • 2020-04-25
      • 2021-08-09
      • 1970-01-01
      相关资源
      最近更新 更多