- 安全导航运算符
即使变量不存在时,也不报错。可以对属性出现null和undefined值进行保护,以防止视图渲染失败
安全导航运算符是ES2020中的新语法,又叫可选链
<p>The hero name is :{{Hero?.name}}</p>
当item为null时,视图仍然渲染,显示的值为
The hero name is :
, 直到后面的name请求出来。
- 非空断言
在ts中,开启--strictNullChecks后,将一个可能是
undefiend
或null
的变量赋给一个有确切类型的变量时,会报错;但在特定情况下,我们很确定那个变量一定不是undefined
或null
,此时可以用非空断言操作符
用了这个操作符的变量,ts则不必再操心,这个变量一定是有值的。非空断言生效的前提是开启--strictNullChecks
- tsconfig.json中设置"strictNullChecks:true"
- tslint.json中设置"no-non-null-assertion:false"
name : string | null = ''
constructor(){
//报错,this.name可能为null,所以不允许赋值给heroName
const hreoName : string = this.name;
//没毛病,因为告诉了ts,这里的this.name一定不是null
const hreoName : string = this.name!;
//以上写法相当于
if(this.name){
const heroName : string = this.name;
}
}
- 类型转换函数 $any()
有时候,绑定的表达式不能或很难指定类型。要消除这种报错,你可以使用
$any()
转换函数来把表达式转换成any
类型假设无法确定item的类型,也就不能确定item是否有
bestByDate
,这时就会报错,可以用$any()
把item
视为any
类型,避免其报错
<p>The item's undeclared best by date is: {{$any(item).bestByDate}}</p>
也可以用这个函数绑定组件中不存在的变量
<p>The item's undeclared best by date is: {{$any(this).bestByDate}}</p>
网友评论