173
在 typescript 的程式語言當中, 使用 ! 驚嘆號的意思就是代表驚嘆號前方的變數(物件)必須是存在的, 如果不存在就會出錯!
有點類似主動防呆的一種用法!!! 避免在這類高階程式語言當中因為將該變數(物件)進行指派或是初始化而造成看不到(不會跳錯誤)的 bug! 以下用個範例解釋!
function TS_test(inputObj: any): void{
console.log("=====================================");
// 完全正常的 case
console.log('Best fruit name is: ' + inputObj.fruit!.name);
// 因為沒有加上 ! ,所以並未強制判斷變數(物件)並要求跳出 error
console.log('Case 1: Best food is: ' + inputObj.food);
// 因為有加上 ! ,因此程式碼會判斷 food 是否存在, 不存在的話就會跳出 error
console.log('Case 2: Best food is: ' + inputObj.food!.name);
console.log("=====================================");
}
const TaiwanBest = {
fruit: {name: 'banana'}
}
TS_test(TaiwanBest);
輸出結果如下
console.log('Case 2: Best food is: ' + inputObj.food!.name);
TypeError: Cannot read properties of undefined (reading 'name')
參考資料來源: https://blog.csdn.net/qubes/article/details/136867140