在前端开发中,我们经常需要处理对象中的嵌套属性或方法,但是当使用嵌套属性或方法时,如果对象不存在或者为空,就会导致程序崩溃。为了解决这个问题,TypeScript 2.0 引入了可选链操作符 ?.,它可以帮助我们简化代码并避免程序崩溃。
可选链操作符简介
可选链操作符 ?. 可以在访问对象属性或方法时,判断对象是否为 null 或 undefined,如果是,则返回 undefined,而不是抛出 TypeError 异常。这样,我们就可以避免在访问对象属性或方法时出现错误,从而提高程序的稳定性和可靠性。
下面是可选链操作符的语法示例:
obj?.prop // 访问属性 obj?.method() // 调用方法
如果 obj 为 null 或 undefined,上述代码将返回 undefined,否则将正常访问属性或方法。
可选链操作符的使用场景
可选链操作符主要用于访问对象属性或方法时,判断对象是否为 null 或 undefined,避免程序崩溃。下面是一些使用场景的示例:
访问嵌套属性
在访问嵌套属性时,如果中间的对象不存在或为空,就会导致程序崩溃。使用可选链操作符可以避免这个问题,例如:
// www.javascriptcn.com code example
const user = {
name: 'Alice',
address: {
city: 'Beijing',
street: 'Tiananmen Square',
},
};
console.log(user.address?.city); // 'Beijing'
console.log(user.address?.country); // undefined调用嵌套方法
在调用嵌套方法时,如果中间的对象不存在或为空,就会导致程序崩溃。使用可选链操作符可以避免这个问题,例如:
// www.javascriptcn.com code example
const user = {
name: 'Alice',
getAddress(): string {
return 'Beijing, Tiananmen Square';
},
};
console.log(user.getAddress?.()); // 'Beijing, Tiananmen Square'
console.log(user.getPhone?.()); // undefined迭代嵌套数组
在迭代嵌套数组时,如果中间的数组不存在或为空,就会导致程序崩溃。使用可选链操作符可以避免这个问题,例如:
// www.javascriptcn.com code example
const users = [
{
name: 'Alice',
hobbies: ['reading', 'traveling'],
},
{
name: 'Bob',
},
];
console.log(users[0]?.hobbies?.[0]); // 'reading'
console.log(users[1]?.hobbies?.[0]); // undefined可选链操作符的注意事项
在使用可选链操作符时,需要注意以下几点:
- 可选链操作符只能用于访问对象属性或方法,不能用于访问变量或函数。
- 可选链操作符只能用于 TypeScript 2.0 及以上版本,不能用于旧版本的 TypeScript 或 JavaScript。
- 可选链操作符只能用于编译时静态检查,不能用于运行时动态判断。如果要动态判断对象是否为 null 或 undefined,可以使用传统的 if 判断语句。
可选链操作符的示例代码
下面是一个使用可选链操作符的示例代码:
// www.javascriptcn.com code example
interface User {
name: string;
address?: {
city: string;
street: string;
};
getPhone?(): string;
}
const user: User = {
name: 'Alice',
address: {
city: 'Beijing',
street: 'Tiananmen Square',
},
getPhone() {
return '1234567890';
},
};
console.log(user.address?.city); // 'Beijing'
console.log(user.address?.country); // undefined
console.log(user.getPhone?.()); // '1234567890'
console.log(user.getFax?.()); // undefined在上述代码中,我们定义了一个接口 User,它包含一个可选的 address 属性和一个可选的 getPhone 方法。然后,我们创建了一个 user 对象,并使用可选链操作符访问它的属性和方法。
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/67da2feaa941bf71341ef0e4