先看以下代码:

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)。
语法

非空断言操作符操作符 ! 可以用于断言操作对象是非 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";

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

TypeScript基础知识点,自己总结的,免费,欢迎下载TypeScript基础知识点,自己总结的,免费,欢迎下载TypeScript基础知识点,自己总结的,免费,欢迎下载TypeScript基础知识点,自己总结的,免费,欢迎下载TypeScript基础知识点,自己总结的,免费,欢迎下载TypeScript基础知识点,自己总结的,免费,欢迎下载TypeScript基础知识点,自己总结的,免费,欢迎下载TypeScript基础知识点,自己总结的,免费,欢迎下载TypeScript基础知识点,自己总结的,免费,欢迎下载TypeScript基础知识点,自己总结的,免费,欢迎下载TypeScript基础知识点,自己总结的,免费,欢迎下载TypeScript基础知识点,自己总结的,免费,欢迎下载TypeScript基础知识点,自己总结的,免费,欢迎下载TypeScript基础知识点,自己总结的,免费,欢迎下载TypeScript基础知识点,自己总结的,免费,欢迎下载TypeScript基础知识点,自己总结的,免费,欢迎下载TypeScript基础知识点,自己总结的,免费,欢迎下载 则是一种防御性编程工具,用于条件地访问可能不存在的属性或方法。是用来强制告诉编译器一个值一定存在,而可选链运算符。服务于不同的目的,尽管它们都与处理可能为。在TypeScript中,非空断言操作符。 Type ‘Function | undefined’ is not assignable to type ‘Function’. Type ‘undefined’ is not assignable to type ‘Function’. 类型’Function | undefined’不能赋值给类型’Function’。 类型’undefined’不能赋值给类型’Function’。 解决:将类型定义为Function | undefined const myFun: Function 非空断言(Non-null Assertion)是 TypeScript 2.0 引入的新特性,用于告诉编译器一个变量不为 `null` 或 `undefined`,在某些场景下可以方便地解决一些类型检查问题。 这个操作符在处理可能为 null 或 undefined 的情况时非常有用,但需要小心使用,因为它绕过了 TypeScript 的类型检查。如果你不能确定,最好使用安全的方式来处理可能为空的值,例如使用条件语句或空值检查。是 TypeScript 中的非空断言操作符,用于告诉编译器某个表达式的值一定不会为。是一个非常有用的非空断言操作符,用于告诉编译器一个表达式的值一定不会为。断言告诉 TypeScript,这个值不会为空,因此可以安全地调用。,因为它绕过了 TypeScript 的类型检查。 在 TypeScript 中,编译器有时会检查代码中的类型不匹配,例如将一个 null 值赋值给一个非空类型变量,此时编译器会发出错误提示。使用非空断言可以告诉编译器该变量的值不会是 null,从而避免编译错误。这种写法通常表示一个非空断言(non-null assertion),它用来告诉编译器该变量的值不会为 null。是否为 null,而会将其视为非空字符串。表示断言该值不会是 null,因此编译器不会检查。在 TypeScript 中,,因此编译器不会检查它的类型。,则整个表达式将返回。 TypeScript 是一种由微软开发的自由和开源的编程语言。它是 JavaScript 的一个超集,而且本质上向这个语言添加了可选的静态类型和基于类的面向对象编程。本文阿宝哥将分享这些...