[TypeScript] 引用物件參數時,為什麼後面要接問號

Leisure Rife
Apr 4, 2021

--

Digamber — Introduction to TypeScript and How Does it Work?

本篇文章屬個人見解,若有錯誤部分,請不吝指教

問題

在寫TypeScript時,常常會看到這樣的程式碼objectA?.paramB ,而這個是代表什麼意思呢?

官方文件解釋

In JavaScript, if you access a property that doesn’t exist, you’ll get the value undefined rather than a runtime error. Because of this, when you read from an optional property, you’ll have to check for undefined before using it.

function printName(obj: { first: string; last?: string }) {  // Error - might crash if 'obj.last' wasn't provided!  console.log(obj.last.toUpperCase());  Object is possibly 'undefined'.Object is possibly 'undefined'.  
if (obj.last !== undefined) {
// OK console.log(obj.last.toUpperCase()); } // A safe alternative using modern JavaScript syntax: console.log(obj.last?.toUpperCase());}

使用時機

所以我們從上面知道,如果objectA後面沒接問號時,而直接使用paramB會發生什麼情況呢?

範例

在下面的這個例子的話,到底該不該加問號呢?個人是覺得應該不要加會比較好,理由是objectA是null時,objectA?.paramB會回傳undefined,這樣不會跳出錯誤,而是會導頁到{domain}/undefined/history,這樣反而要抓錯的時候不好抓,若是寫objectA.paramB則會跑出TypeError頁面,馬上就知道有問題。有空的話再來寫建議加的範例。

...
export default defineComponent({
setup() {
let vm = getCurrentInstance()
vm = null
const router = useRouter()
router.push('/${vm?.$route.params.productId}/history/')
})
...

結論

目前個人的見解的話,該加或不加還是應該要看情況而定。而並不是因為定義的object是不是可為nullable。但TypeScript還不是很熟,也許這個觀點會再被自己推翻。

參考資料

--

--

Leisure Rife
Leisure Rife

Written by Leisure Rife

尋找著在忙忙碌碌的世界中,最適合自己的生活,也或許不斷的移動城市是我的生活方式

No responses yet