如何设置空值或等效于字段?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何设置空值或等效于字段?相关的知识,希望对你有一定的参考价值。

我有这个组件状态:

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;

以上是关于如何设置空值或等效于字段?的主要内容,如果未能解决你的问题,请参考以下文章