- 安全導(dǎo)航運算符
即使變量不存在時典挑,也不報錯。可以對屬性出現(xiàn)null和undefined值進(jìn)行保護(hù)曙寡,以防止視圖渲染失敗
安全導(dǎo)航運算符是ES2020中的新語法,又叫可選鏈
<p>The hero name is :{{Hero?.name}}</p>
當(dāng)item為null時寇荧,視圖仍然渲染举庶,顯示的值為
The hero name is :
, 直到后面的name請求出來。
- 非空斷言
在ts中揩抡,開啟--strictNullChecks后户侥,將一個可能是
undefiend
或null
的變量賦給一個有確切類型的變量時,會報錯峦嗤;但在特定情況下蕊唐,我們很確定那個變量一定不是undefined
或null
,此時可以用非空斷言操作符
用了這個操作符的變量寻仗,ts則不必再操心刃泌,這個變量一定是有值的。非空斷言生效的前提是開啟--strictNullChecks
- tsconfig.json中設(shè)置"strictNullChecks:true"
- tslint.json中設(shè)置"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!;
//以上寫法相當(dāng)于
if(this.name){
const heroName : string = this.name;
}
}
- 類型轉(zhuǎn)換函數(shù) $any()
有時候曹体,綁定的表達(dá)式不能或很難指定類型俗扇。要消除這種報錯,你可以使用
$any()
轉(zhuǎn)換函數(shù)來把表達(dá)式轉(zhuǎn)換成any
類型假設(shè)無法確定item的類型箕别,也就不能確定item是否有
bestByDate
铜幽,這時就會報錯滞谢,可以用$any()
把item
視為any
類型,避免其報錯
<p>The item's undeclared best by date is: {{$any(item).bestByDate}}</p>
也可以用這個函數(shù)綁定組件中不存在的變量
<p>The item's undeclared best by date is: {{$any(this).bestByDate}}</p>