持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第12天,点击查看活动详情
先看以下代码:
function handler (arg: string | null | undefined) {
let str: string = arg;
// ...
}
复制代码
对于以上代码, TypeScript编译器会提示以下错误信息:
Type 'string | null | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
复制代码
要解决以上问题,我们可以加个条件判断:
function handler (arg: string | null | undefined) {
let str: string;
if (arg) {
str = arg;
}
// ...
}
复制代码
此外, 可以使用TypeScript2.0中提供的非空断言操作符(non-null-assertion-operator)。
语法
x!
非空断言操作符操作符 ! 可以用于断言操作对象是非 null 和非 undefined 类型。即: x! 将从 x 值域中排除 null 和 undefined 。
所以以上代码可以改造为:
function handler (arg: string | null | undefined) {
let str: string = arg!; // 没毛病
str.split('');
// ...
}
复制代码
看下编译结果:
"use strict";
function handler(arg) {
let str = arg;
str.split('');
// ...
}
复制代码
可以看出!非空断言操作符从编译生成的JS代码中移除掉了, 如果handler函数调用时传入null或undefined时,会出现以下运行时错误:
Uncaught TypeError: Cannot read properties of undefined (reading 'split')
复制代码
所以在实际使用时需要注意。
注意: 非空断言操作符仅在启用 strictNullChecks 标志的时候才生效。当关闭该标志时,编译器不会检查 undefined 类型和 null 类型的赋值。
可选链运算符
先看以下代码:
type AlbumAPIResponse = {
title: string;
artist?: {
name: string;
bio?: string;
previousAlbums?: string[];
};
};
const album: AlbumAPIResponse = {
title: 'test'
};
const maybeArtistBio = album.artist && album.artist.bio || undefined;
const maybeArtistBioElement = album ? album.artist ? album.artist.bio ? album.artist.bio : undefined: undefined :undefined;
const maybeFirstPreviousAlbum = album.artist && album.artist.previousAlbums && album.artist.previousAlbums[0] || undefined;
复制代码
为了获取bio 或者 previousAlbums 可谓是煞费苦心。
现在可以使用TypeScript3.7中提供的可选链(Optional Chaining), 有了可选链后,我们编写代码时如果遇到 null 或 undefined 就可以立即停止某些表达式的运行,直接返回undefined .与函数调用一起使用时,如果给定的函数不存在,则返回 undefined。 核心是?.操作符。
语法
obj?.prop
obj?.[expr]
arr?.[index]
func?.(args)
使用
- 可选属性访问
那么以上代码就可以精简为:
const maybeArtistBioElement = album?.["artist"]?.["bio"];
const maybeFirstPreviousAlbum = album?.artist?.previousAlbums?.[0];
复制代码
是不是精简很多了。
注意: ?.与&& 并不是完全等价。 && 专门用于检测 falsy 值,比如空字符串、0、-0 、0n、NaN、null、undefined 和 false 等。而 ?. 只会验证对象是否为 null 或 undefined,对于0或空字符串来说,并不会出现 “短路”。
- 可选元素访问
其行为类似于可选属性访问,但允许我们访问非标识符属性(例如任意字符串、数字和symbol). 以下是基于索引访问数组元素:
function tryGetFirstElement<T>(arr?: T[]) {
return arr?.[0];
}
复制代码
编译结果如下:
"use strict";
function tryGetFirstElement(arr) {
return arr === null || arr === void 0 ? void 0 : arr[0];
}
复制代码
所以在使用可链接后, 就不需要手动编写检查数组是否为null或undefined的保护性代码了。
作者:细路
链接:juejin.cn/post/710759…
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。