<p>typescript編譯時,當我們<strong>開啟嚴格模式</strong>時么介,下面的代碼就會報錯:</p><pre>function?doSomething(x:?string?|?null)?{
????console.log("Hello,?"?+?x.toUpperCase());
}</pre><p>編譯錯誤:</p><pre>hello.ts:56:29?-?error?TS2531:?Object?is?possibly?'null'.
56?????console.log("Hello,?"?+?x.toUpperCase());</pre><p>當我們在調用變量x的方法時责鳍,增加后綴!和烫映?時袱衷,這個編譯錯誤都會消失:</p><pre>x!.toUpperCase()?
x?.toUpperCase()</pre><p><strong>那這兩者到底有什么區(qū)別呢检吆?</strong></p><p>后綴是?</p><pre>function?doSomething(x:?string?|?null)?{
????console.log("Hello,?"?+?x?.toUpperCase());
}
doSomething(null);</pre><p>輸出是:</p><pre>Hello,?undefined</pre><p>后綴是!</p><pre>function?doSomething(x:?string?|?null)?{
????console.log("Hello,?"?+?x!.toUpperCase());
}
doSomething(null);</pre><p>輸出是:</p><pre>Uncaught?TypeError?TypeError:?Cannot?read?properties?of?null?(reading?'toUpperCase')</pre><p><strong>結論:</strong></p><ul><li><p>后綴是!,只是告訴typescript編譯器對于null和undefined不做顯示的檢查曹洽,生成的js文件中還是x.toUpperCase()鳍置,如果此時x為null,那么就會出現(xiàn)運行時異常</p></li><li><p>后綴是?送淆,代表是一個空判斷税产,只有非空是,才會執(zhí)行x.toUpperCase()偷崩,生成的js文件中是增加了null或者undefined判斷的辟拷,生成的js是(x === null || x === void 0 ? void 0 : x.toUpperCase())</p></li></ul>