ArkTS 可选链?、强制非空断言??、空值合并运算??

空安全

null的含义

null 是一个特殊的字面量值,用于表示一个变量没有指向任何对象。当变量值为null时,使用这个变量是没有意义,甚至会引发程序异常,所以默认情况下ArkTS中的所有类型的值都是不可为null值;要想变量的值为null,必须明确指定null类型。

let x: string = null    // 编译时错误
let y: string | null = null	//编译通过

在开发中经常存在这么一种情况:一个变量的值可能为null、也可能是一个具体对象,但是在执行之前不能明确该变量的值是null还是一个对象。 此时使用该对象调用其方法时,就必须使用非空判断

let flag = true
let stu: student | null = null
if (flag) {
  stu = new student('张三', 20)
}
if (stu != null) {
  stu.show()
}
console.info("over")

可选链

为了简化非空判断的书写,可以使用可选链的语法:对象变量?.方法名()

//通过调整flag的值,控制stu是否为null
let flag = true
let stu: student | null = null
if (flag) {
  stu = new student('张三', 20)
}
stu?.show() //语义:stu不为null,才调用show方法,否则啥也不敢
console.info("over")

! 强制非空断言

如果你自己主动明确该变量不为空,想要强制使用该变量,则可以使用变量名!强制断言变量非空,跳过编译检查。

let flag = true
let stu: student | null = null
if (flag) {
  stu = new student('张三', 20)
}
stu!.show() //语义:不管stu是否为null,强制调用show()
console.info("over")

?? 空值合并运算符

如下代码表示,a不为null或者undefined时,res1等于a值,否则res1="hello"

let a: string | undefined | null = undefined
let res1 = (a != null && a != undefined) ? a : "hello"

在以上的场景下,可以将三元运算采用??进行简化书写,其语义是一样的。

let b: string | undefined | null = undefined
let res2 = a??"hello"	//a不为null或者undefined时,res2等于a值,否则res2="hello"

恭喜你,空安全学完了,手动撒花🎉🎉🎉

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值