我有这个组件状态:
interface Person {
name: string;
surname: string;
}
interface CompState{
//...fields ...
person?: Person;
}
render() {
if(this.state.person){
const comp = <div>{this.person.name + this.person.surname}</div>
}
...
}
在我的一个处理程序中,我想“清空”渲染的组件,所以我只想这样做:
newState.person = null; //Type 'null' is not assignable to type Person | undefined
我究竟做错了什么?在打字稿中将变量重置为null是不可能的?
以下两个在打字稿中是等效的:
person?: Person;
person: Person | undefined;
因此,如果您想“取消设置”某个值,则必须指定undefined
。否则,如果你真的想使用null
,你仍然可以
person: Person | null;