对象在打字稿中可能为'null'

时间:2019-01-24 10:08:53

标签: javascript reactjs 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仍然告诉我:

enter image description here

即使我尝试过:

enter image description here

还有“!”也行不通

enter image description here

如您所见,“当前”对象不能为null,因为在使用它之前我进行了null检查。

但是打字稿引擎仍然向我显示该错误。

我想知道的是,因为我使用null值初始化了当前对象,但是ts无法从setState中找出类型,所以它始终将当前状态为null?

2 个答案:

答案 0 :(得分:2)

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

constructor(props) {
    super(props);

    this.state = {
        current: null;
    }
}

答案 1 :(得分:2)

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

state: IRoleAddState = {
    current: null
};

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

相关问题