TypeScript 中可選鏈是如何工作的?


在本文中,您將瞭解 TypeScript 中可選鏈是如何工作的。可選鏈運算子 (?.) 用於訪問物件的屬性。如果物件的屬性為 null 或未定義,則返回 'undefined'。讓我們首先了解一下 TypeScript 是什麼。

TypeScript 是一種強型別程式語言,它基於 JavaScript,在任何規模下都能為您提供更好的工具。用 TypeScript 編寫的程式碼可以轉換為在任何相容 JavaScript 的環境中執行。TypeScript 理解 JavaScript,並使用型別推斷來提供出色的工具,而無需額外的程式碼。

示例 1

在這個例子中,我們使用了可選鏈運算子並呼叫了兩次函式。第一次呼叫返回物件的屬性,第二次呼叫返回 'undefined' -

let displayMessage = (firstWord , lastWord) => {
   return "Message : " + firstWord + " " + lastWord;
}
console.log("The first input words are Good and Evening")
console.log("The Display message is: ")
console.log(displayMessage("Good", "Evening"));

console.log("
The first input words are Good") console.log("The Display message is: ") console.log(displayMessage("Good"));

輸出

The first input words are Good and Evening
The Display message is: 
Message : Good Evening
The first input words are Good and Morning
The Display message is: 
Message : Good undefined

解釋

  • 步驟 1 - 定義一個名為 'displayMessage' 的函式,該函式接收兩個字串並將其列印在一起。

  • 步驟 2 - 使用兩個字串呼叫該函式並列印結果。

  • 步驟 3 - 只用一個字串呼叫該函式並顯示結果。

示例 2

type User = {
   id: number;
   name?: {
      firstWord: string;
      lastWord?: string;
   }
};
const users: User[] = [{
   id: 1,
   name: {
      firstWord: "Welcome"
   }
},
{
   id: 2,
   name: {
      firstWord: "Good",
      lastWord: "Evening"
   }
},
{
   id: 3
},
];
console.log("The first input word is Welcome")
console.log("The second input words are Good and Evening")

console.log("After calling the values, the result is")
users.map(element => console.log(element.name?.lastWord));
users.map(element => console.log(element.name?.lastWord));

輸出

The first input word is Welcome
The second input words are Good and Evening

After calling the values, the result is

undefined 
"Evening" 
undefined 

解釋

  • 步驟 1 - 定義多個變數,這些變數接收不同的值(例如字串或數字)作為引數,並且數量也不同。

  • 步驟 2 - 呼叫這些變數。如果引數型別和值匹配,則顯示這些變數。如果引數不匹配,則返回 'undefined'。

更新於: 2023年2月16日

317 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告