可选链在 TypeScript 中如何工作?

typescriptserver side programmingprogramming

在本文中,您将了解可选链在 TypeScript 中的工作方式。可选链运算符 (?.) 访问对象的属性。如果对象属性为 null 或未定义,则返回"undefined"。让我们首先了解什么是 TypeScript。

基于 JavaScript 的强类型编程语言 TypeScript 可为您提供任何规模的更好工具。用 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 − 仅使用一个字符串调用该函数并显示结果。

Example 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"。


相关文章