TypeScript 如何使用可选链呢
在本文中,我们将尝试理解如何在TypeScript中执行和分析可选链的工作。
TypeScript的可选链:
- TypeScript的可选链是搜索和调用可能为空的变量、方法和参数的过程。
- 这个特性允许开发人员停止遇到错误,这些错误通常在事物未定义时出现,而且他们可以通过这个特性轻松处理未定义的事物。
可选链是如何工作的呢?
- 可选链实际上是以一种有些棘手的方式工作的,它首先检查特定变量或函数是否可用。
- 如果该变量或函数在文件中可用,它将继续检查后续提到的变量或函数。
- 如果该变量不可用,它立即停止进一步检查,并返回“undefined”,用户可以使用特定的逻辑轻松处理它。
让我们首先分析如何在TypeScript中将参数(在函数中工作时)或变量声明为可选变量。
声明可选参数的语法: 我们可以使用以下语法将变量声明为 TypeScript 中的可选变量(使用“?”操作符将任何变量声明为可选变量)-
parameter_name? : return_type
Example 1: 在这个示例中,我们将使用一个示例来实现上面所示的语法。
JavaScript
let displayName = (firstName: string , lastName? : string) => {
return "Name : " + firstName + " " + lastName;
}
console.log(displayName("Hello", "World"));
console.log(displayName("GeeksforGeeks"));
输出: 以上示例代码将为两者生成输出,但是在只传递一个参数的情况下,它会生成一个错误,仅显示“undefined”。
Name : Hello World
Name : GeeksforGeeks undefined
现在我们已经了解了如何在TypeScript中声明可选参数。现在让我们看看如何在TypeScript中执行可选链接,以下是示例:
示例2: 在这个示例中,我们将实现可选链接,同时显示结果或输出。
Javascript
type User = {
id: number;
name?: {
firstName: string;
lastName?: string;
}
};
const users: User[] = [{
id: 1,
name: {
firstName: "GeeksforGeeks"
}
},
{
id: 2,
name: {
firstName: "Hello",
lastName: "World"
}
},
{
id: 3
},
];
users.map(element => console.log(element.name?.lastName));
输出:
undefined
World
undefined
示例 3: 在这个示例中,我们将展示不同风格或技巧中的可选链接。
JavaScript
type personDetails = {
name : string,
details? : {
age?: number,
location?: string,
}
}
let person_one: personDetails = {
name: "GeeksforGeeks",
details : {
age: 20,
location: "Noida"
}
}
let person_two: personDetails = {
name: "GeeksforGeeks",
details : {
location: "Noida"
}
}
let person_three: personDetails = {
name: "GeeksforGeeks",
details : {
age: 20,
}
}
let data_1 = person_one.name + " "
+ person_one.details?.age + " "
+ person_one.details?.location;
console.log(data_1);
let data_2 = person_two.name + " "
+ person_two.details?.age + " "
+ person_two.details?.location;
console.log(data_2);
let data_3 = person_three.name + " "
+ person_three.details?.age + " "
+ person_three.details?.location;
console.log(data_3);
输出:
GeeksforGeeks 20 Noida
GeeksforGeeks undefined Noida
GeeksforGeeks 20 undefined
极客教程