理解 TypeScript 类型收窄

创建了一个 “重学TypeScript” 的微信群,想加群的小伙伴,加我微信 “semlinker”
,备注重学TS。

本文是 ”重学TS系列“ 第 29
篇文章,感谢您的阅读!

一、类型收窄

TypeScript 类型收窄就是从宽类型转换成窄类型的过程。类型收窄常用于处理联合类型变量的场景,一个常见的例子是非空检查:

// Type is HTMLElement | null
const el = document.getElementById("foo");
if (el) {
  // Type is HTMLElement
  el.innerHTML = "semlinker"; 
} else {
  // Type is null
  alert("id为foo的元素不存在");
}

如果 el 为 null,则第一个分支中的代码将不会执行。因此,TypeScript 能够从此代码块内的联合类型中排除 null 类型,从而产生更窄的类型,更易于使用。
此外,你还可以通过抛出异常或从分支返回,来收窄变量的类型。例如:

// Type is HTMLElement | null
const el = document.getElementById("foo");
if (!el) throw new Error("找不到id为foo的元素");
// Type is HTMLElement
el.innerHTML = "semlinker";

其实在 TypeScript 中,有许多方法可以收窄变量的类型。比如使用 instanceof 运算符:

function contains(text: string, search: string | RegExp) {
  if (search instanceof RegExp) {
    // Type is RegExp
    return !!search.exec(text);
  }
  // Type is string
  return text.includes(search);
}

当然属性检查也是可以的:

interface Admin {
  name: string;
  privileges: string[];
}

interface Employee {
  name: string;
  startDate: Date;
}

type UnknownEmployee = Employee | Admin;

function printEmployeeInformation(emp: UnknownEmployee) {
  console.log("Name: " + emp.name);
  if ("privileges"in emp) {
    // Type is Admin
    console.log("Privileges: " + emp.privileges);
  }
  if ("startDate"in emp) {
    // Type is Employee
    console.log("Start Date: " + emp.startDate);
  }
}

使用一些内置的函数,比如 Array.isArray
也能够收窄类型:

function contains(text: string, terms: string | string[]) {
  const termList = Array.isArray(terms) ? terms : [terms];
  termList; // Type is string[]
  // ...
}

一般来说 TypeScript 非常擅长通过条件来判别类型,但在处理一些特殊值时要特别注意 —— 它可能包含你不想要的东西!例如,以下从联合类型中排除 null 的方法是错误的:

const el = document.getElementById("foo"); // Type is HTMLElement | null
if (typeof el === "object") {
  el; // Type is HTMLElement | null
}

因为在 JavaScript 中 typeof null
的结果是 “object” ,所以你实际上并没有通过这种检查排除 null
值。除此之外,falsy 的原始值也会产生类似的问题:

function foo(x?: number | string | null) {
  if (!x) {
    x; // Type is string | number | null | undefined
  }
}

因为空字符串和 0 都属于 falsy 值,所以在分支中 x 的类型可能是 string 或 number 类型。帮助类型检查器缩小类型的另一种常见方法是在它们上放置一个明确的 “标签”:

interface UploadEvent {
  type: "upload";
  filename: string;
  contents: string;
}

interface DownloadEvent {
  type: "download";
  filename: string;
}

type AppEvent = UploadEvent | DownloadEvent;

function handleEvent(e: AppEvent) {
  switch (e.type) {
    case "download":
      e; // Type is DownloadEvent 
      break;
    case "upload":
      e; // Type is UploadEvent 
      break;
  }
}

这种模式也被称为 ”标签联合“ 或 ”可辨识联合“,它在 TypeScript 中的应用范围非常广。
如果 TypeScript 不能识别出类型,你甚至可以引入一个自定义函数来帮助它:

function isInputElement(el: HTMLElement): el is HTMLInputElement {
  return "value" in el;
}

function getElementContent(el: HTMLElement) {
  if (isInputElement(el)) {
    // Type is HTMLInputElement
    return el.value;
  }
  // Type is HTMLElement
  return el.textContent;
}

这就是所谓的 “用户定义类型保护”。 el is HTMLInputElement
,作为返回类型告诉类型检查器,如果函数返回true,则 el 变量的类型就是 HTMLInputElement。

类型保护是可执行运行时检查的一种表达式,用于确保该类型在一定的范围内。换句话说,类型保护可以保证一个字符串是一个字符串,尽管它的值也可以是一个数值。类型保护与特性检测并不是完全不同,其主要思想是尝试检测属性、方法或原型,以确定如何处理值。
一些函数能够使用类型保护来执行数组或对象的类型收窄。例如,如果你在一个数组中进行一些查找,你可能会得到一个 nullable 类型的数组:

const supermans = ["Qinhw", "Pingan8787", "Semlinker", "Kaquko", "Lolo"];
const members = ["Semlinker", "Lolo"]
  .map((who) => supermans.find((n) => n === who))
// Type is (string | undefined)[]

这时你可能想到使用 filter 方法过滤掉未定义的值:

const supermans = ["Qinhw", "Pingan8787", "Semlinker", "Kaquko", "Lolo"];
const members = ["Semlinker", "Lolo"]
  .map((who) => supermans.find((n) => n === who))
  .filter((who) => who !== undefined);
// Type is (string | undefined)[]

可惜的是 TypeScript 也无法理解你的意图,但是如果你使用一个类型保护函数的话就可以:

function isDefined(x: T | undefined): x is T {
  return x !== undefined;
}

const supermans = ["Qinhw", "Pingan8787", "Semlinker", "Kaquko", "Lolo"];
const members = ["Semlinker", "Lolo"]
  .map((who) => supermans.find((n) => n === who))
  .filter(isDefined);
// Type is string[]

二、全面性检查

在 TypeScript 中我们可以利用类型收窄和 never 类型的特性来全面性检查,比如:

type Foo = string | number;

function controlFlowAnalysisWithNever(foo: Foo) {
  if(typeof foo === "string") {
    // 这里 foo 被收窄为 string 类型
  } else if(typeof foo === "number") {
    // 这里 foo 被收窄为 number 类型
  } else {
    // foo 在这里是 never
    const check: never = foo;
  }
}

注意在 else 分支里面,我们把收窄为 never 的 foo 赋值给一个显示声明的 never 变量。如果一切逻辑正确,那么这里应该能够编译通过。但是假如后来有一天你的同事修改了 Foo 的类型:

type Foo = string | number | boolean;

然而他忘记同时修改 controlFlowAnalysisWithNever
方法中的控制流程,这时候 else 分支的 foo 类型会被收窄为 boolean
类型,导致无法赋值给 never 类型,这时就会产生一个编译错误。通过这个方式,我们可以确保

controlFlowAnalysisWithNever
方法总是穷尽了 Foo 的所有可能类型。 通过这个示例,我们可以得出一个结论: 使用 never 避免出现新增了联合类型没有对应的实现,目的就是写出类型绝对安全的代码。

三、总结

理解 TypeScript 中的类型收窄将帮助你建立一个关于类型推断如何工作的认知,进一步理解错误,它通常与类型检查器有更紧密的联系。
Dan Vanderkam 大神写的 ”62 Specific Ways to Improve Your TypeScript“ 这本书内容挺不错的,有兴趣的读者可以阅读一下。