空值检查
2025/12/22小于 1 分钟
空值检查
空安全
默认情况下,ArkTS中的所有类型都是不可为空的,因此类型的值不能为空。这类似于TypeScript的严格空值检查模式(strictNullChecks),但规则更严格。
一般使用三种方式,防止变量为空
if
if(x==null){
x=''
}空值合并运算符
空值合并二元运算符??用于检查左侧表达式的求值是否等于null。如果是,则表达式的结果为右侧表达式;否则,结果为左侧表达式。
换句话说,a ?? b等价于三元运算符a != null ? a : b。
在以下示例中,getNick方法如果设置了昵称,则返回昵称;否则,返回空字符串:
class Person {
// ...
nick: string | null = null
getNick(): string {
return this.nick ?? '';
}
}可选链
在访问对象属性时,如果该属性是undefined或者null,可选链运算符会返回undefined。
class Person {
nick: string | null = null
spouse?: Person
setSpouse(spouse: Person): void {
this.spouse = spouse;
}
getSpouseNick(): string | null | undefined {
return this.spouse?.nick;
}
constructor(nick: string) {
this.nick = nick;
this.spouse = undefined;
}
}补充知识点
