TypeScript基础之非空断言操作符、可选链运算符、空值合并运算符

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第11天,点击查看活动详情

非空断言

先看以下代码:

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 值域中排除 nullundefined

所以以上代码可以改造为:

function handler (arg: string | null | undefined) {
  let str: string = arg!;   // 没毛病 
  str.split('');
  // ...  
}
复制代码

看下编译结果:

"use strict";
function handler(arg) {
  let str = arg;
  str.split('');
    // ...  
}
复制代码

可以看出!非空断言操作符从编译生成的JS代码中移除掉了, 如果handler函数调用时传入nullundefined时,会出现以下运行时错误:

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)

使用

  1. 可选属性访问

那么以上代码就可以精简为:

const maybeArtistBioElement = album?.["artist"]?.["bio"];

const maybeFirstPreviousAlbum = album?.artist?.previousAlbums?.[0];  
复制代码

是不是精简很多了。

注意: ?.&& 并不是完全等价。 && 专门用于检测 falsy 值,比如空字符串、0、-0 、0n、NaN、null、undefined 和 false 等。而 ?. 只会验证对象是否为 nullundefined,对于0空字符串来说,并不会出现 “短路”

  1. 可选元素访问

其行为类似于可选属性访问,但允许我们访问非标识符属性(例如任意字符串、数字和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的保护性代码了。

  1. 尝试调用一个可能不存在的方法
async function makeRequest(url: string, log?: (msg: string) => void) {
  log?.(`Request started at ${new Date().toISOString()}`);
  // 以上代码等价于下面 
  //   if (log != null) {
  //       log(`Request started at ${new Date().toISOString()}`);
  //   }
  const result = (await fetch(url)).json();
  log?.(`Request finished at ${new Date().toISOString()}`);
  return result;
}
复制代码

空值合并运算符

先看以下代码:

interface AppConfiguration {
  name: string;
  items: number;
  active: boolean;
}

function updateApp(config: Partial<AppConfiguration>) { 
  config.name = typeof config.name === "string" ? config.name : "(no name)";
  config.items = typeof config.items === "number" ? config.items : -1;
  config.active = typeof config.active === "boolean" ? config.active : true;
}
复制代码

注意: Partial<T> 将类型的属性变成可选
那么Partial<AppConfiguration>相当于:

interface AppConfiguration {
  name?: string;
  items?: number;
  active?: boolean;
}
复制代码

以上代码中我们需要先利用typeof判断属性类型是否正确,正确就赋值,否则就是默认值。
我们不能使用||, 因为

'' || "(no name)" ;   // 值是"(no name)"不是 ""
0 || -1;    // 会返回-1
false || true;    // 会返回true
复制代码

现在可以使用TypeScript3.7中提供的空值合并运算符。
当左侧操作数为 null 或 undefined 时,其返回右侧的操作数,否则返回左侧的操作数。。 与逻辑或 || 运算符不同,逻辑或会在左操作数为 falsy 值时返回右侧操作数。也就是说,如果你使⽤|| 来为某些变量设置默认的值时,你可能会遇到意料之外的⾏为。⽐如为 falsy 值(空字符串、0、-0 、0n、NaN、null、undefined 和 false)时。
语法

leftExpr ?? rightExpr

使用

  1. 为常量提供默认值,保证常量不为 null 或者 undefined

以上代码可改造如下:

function updateApp(config: Partial<AppConfiguration>) {
  config.name = config.name ?? "(no name)";
  config.items = config.items ?? -1;
  config.active = config.active ?? true;
}
复制代码
  1. 短路

与 OR 和 AND 逻辑操作符相似,当左表达式不为 null 或 undefined 时,不会对右表达式进行求值。

function A() { console.log('函数 A 被调用了'); return undefined; }
function B() { console.log('函数 B 被调用了'); return false; }
function C() { console.log('函数 C 被调用了'); return "foo"; }

console.log( A() ?? C() );
// 依次打印 "函数 A 被调用了"、"函数 C 被调用了"、"foo"
复制代码

编译结果(编译目标设为ES2015)如下:

"use strict";
var _a;
function A() { console.log('函数 A 被调用了'); return undefined; }
function B() { console.log('函数 B 被调用了'); return false; }
function C() { console.log('函数 C 被调用了'); return "foo"; }
console.log((_a = A()) !== null && _a !== void 0 ? _a : C());
复制代码

输出结果解释: A() 返回了 undefined,所以操作符两边的表达式都被执行了

注意: 不能与 AND 或 OR 操作符共用
将 ?? 直接与 AND(&&)和 OR(||)操作符组合使用是不可取的(应当是因为空值合并操作符和其他逻辑操作符之间的运算优先级/运算顺序是未定义的)。

null || undefined ?? "foo";  // '||' and '??' operations cannot be mixed without parentheses.
true || undefined ?? "foo";  // '||' and '??' operations cannot be mixed without parentheses.
复制代码

但是,如果使用括号来显式表明运算优先级,是没有问题的:

(null || undefined ) ?? "foo";
复制代码

参考资料

www.typescriptlang.org/docs/handbo…
developer.mozilla.org/zh-CN/docs/…

猜你喜欢

转载自juejin.im/post/7107598535096270856