而除了类型的创建以外,类型的安全保障同样属于类型工具的能力之一,我们本节要介绍的就是两个主要用于类型安全的类型工具:类型查询操作符类型守卫

类型查询操作符:熟悉又陌生的 typeof

TypeScript 存在两种功能不同的 typeof 操作符。我们最常见的一种 typeof 操作符就是 JavaScript 中,用于检查变量类型的 typeof ,它会返回 “string” / “number” / “object” / “undefined” 等值。而除此以外, TypeScript 还新增了用于类型查询的 typeof ,即 Type Query Operator,这个 typeof 返回的是一个 TypeScript 类型:

  1. const str = "linbudu";
  2. const obj = { name: "linbudu" };
  3. const nullVar = null;
  4. const undefinedVar = undefined;
  5. const func = (input: string) => {
  6. return input.length > 10;
  7. }
  8. type Str = typeof str; // "linbudu"
  9. type Obj = typeof obj; // { name: string; }
  10. type Null = typeof nullVar; // null
  11. type Undefined = typeof undefined; // undefined
  12. type Func = typeof func; // (input: string) => boolean

你不仅可以直接在类型标注中使用 typeof,还能在工具类型中使用 typeof。

  1. const func = (input: string) => {
  2. return input.length > 10;
  3. }
  4. const func2: typeof func = (name: string) => {
  5. return name === 'linbudu'
  6. }

这里我们暂时不用深入了解 ReturnType 这个工具类型,只需要知道它会返回一个函数类型中返回值位置的类型:

  1. const func = (input: string) => {
  2. return input.length > 10;
  3. }
  4. // boolean
  5. type FuncReturnType = ReturnType<typeof func>;

绝大部分情况下,typeof 返回的类型就是当你把鼠标悬浮在变量名上时出现的推导后的类型,并且是最窄的推导程度(即到字面量类型的级别)。你也不必担心混用了这两种 typeof,在逻辑代码中使用的 typeof 一定会是 JavaScript 中的 typeof,而类型代码(如类型标注、类型别名中等)中的一定是类型查询的 typeof 。同时,为了更好地避免这种情况,也就是隔离类型层和逻辑层,类型查询操作符后是不允许使用表达式的:

  1. const isInputValid = (input: string) => {
  2. return input.length > 10;
  3. }
  4. // 不允许表达式
  5. let isValid: typeof isInputValid("linbudu");

类型守卫

TypeScript 中提供了非常强大的类型推导能力,它会随着你的代码逻辑不断尝试收窄类型,这一能力称之为类型的控制流分析(也可以简单理解为类型推导)。
这么说有点抽象,我们可以想象有一条河流,它从上而下流过你的程序,随着代码的分支分出一条条支流,在最后重新合并为一条完整的河流。在河流流动的过程中,如果遇到了有特定条件才能进入的河道(比如 if else 语句、switch case 语句等),那河流流过这里就会收集对应的信息,等到最后合并时,它们就会嚷着交流:“我刚刚流过了一个只有字符串类型才能进入的代码分支!” “我刚刚流过了一个只有函数类型才能进入的代码分支!”……就这样,它会把整个程序的类型信息都收集完毕。

  1. function foo (input: string | number) {
  2. if(typeof input === 'string') {}
  3. if(typeof input === 'number') {}
  4. // ...
  5. }

我们在 never 类型一节中学到的也是如此。在类型控制流分析下,每流过一个 if 分支,后续联合类型的分支就少了一个,因为这个类型已经在这个分支处理过了,不会进入下一个分支:

  1. declare const strOrNumOrBool: string | number | boolean;
  2. if (typeof strOrNumOrBool === "string") {
  3. // 一定是字符串!
  4. strOrNumOrBool.charAt(1);
  5. } else if (typeof strOrNumOrBool === "number") {
  6. // 一定是数字!
  7. strOrNumOrBool.toFixed();
  8. } else if (typeof strOrNumOrBool === "boolean") {
  9. // 一定是布尔值!
  10. strOrNumOrBool === true;
  11. } else {
  12. // 要是走到这里就说明有问题!
  13. const _exhaustiveCheck: never = strOrNumOrBool;
  14. throw new Error(`Unknown input type: ${_exhaustiveCheck}`);
  15. }

在这里,我们实际上通过 if 条件中的表达式进行了类型保护,即告知了流过这里的分析程序每个 if 语句代码块中变量会是何类型。这即是编程语言的类型能力中最重要的一部分:与实际逻辑紧密关联的类型。我们从逻辑中进行类型地推导,再反过来让类型为逻辑保驾护航。

is 关键字 + 预期类型

前面我们说到,类型控制流分析就像一条河流一样流过,那 if 条件中的表达式要是现在被提取出来了怎么办?

  1. function isString(input: unknown): boolean {
  2. return typeof input === "string";
  3. }
  4. function foo(input: string | number) {
  5. if (isString(input)) {
  6. // 类型“string | number”上不存在属性“replace”。
  7. (input).replace("linbudu", "linbudu599")
  8. }
  9. if (typeof input === 'number') { }
  10. // ...
  11. }

奇怪的事情发生了,我们只是把逻辑提取到了外面而已,如果 isString 返回了 true,那 input 肯定也是 string 类型啊?
想象类型控制流分析这条河流,刚流进 if (isString(input)) 就戛然而止了。因为 isString 这个函数在另外一个地方,内部的判断逻辑并不在函数 foo 中。这里的类型控制流分析做不到跨函数上下文来进行类型的信息收集(但别的类型语言中可能是支持的)。
实际上,将判断逻辑封装起来提取到函数外部进行复用非常常见。为了解决这一类型控制流分析的能力不足, TypeScript 引入了 is 关键字来显式地提供类型信息:

  1. function isString(input: unknown): input is string {
  2. return typeof input === "string";
  3. }
  4. function foo(input: string | number) {
  5. if (isString(input)) {
  6. // 正确了
  7. (input).replace("linbudu", "linbudu599")
  8. }
  9. if (typeof input === 'number') { }
  10. // ...
  11. }

isString 函数称为类型守卫,在它的返回值中,我们不再使用 boolean 作为类型标注,而是使用 input is string 这么个奇怪的搭配,拆开来看它是这样的:

  • input 函数的某个参数;
  • is string,即 is 关键字 + 预期类型,即如果这个函数成功返回为 true,那么 is 关键字前这个入参的类型,就会被这个类型守卫调用方后续的类型控制流分析收集到

需要注意的是,类型守卫函数中并不会对判断逻辑和实际类型的关联进行检查:

  1. function isString(input: unknown): input is number {
  2. return typeof input === "string";
  3. }
  4. function foo(input: string | number) {
  5. if (isString(input)) {
  6. // 报错,在这里变成了 number 类型
  7. (input).replace("linbudu", "linbudu599")
  8. }
  9. if (typeof input === 'number') { }
  10. // ...
  11. }

从这个角度来看,其实类型守卫有些类似于类型断言,但类型守卫更宽容,也更信任你一些。你指定什么类型,它就是什么类型。 除了使用简单的原始类型以外,我们还可以在类型守卫中使用对象类型、联合类型等,比如下面我开发时常用的两个守卫:

  1. export type Falsy = false | "" | 0 | null | undefined;
  2. export const isFalsy = (val: unknown): val is Falsy => !val;
  3. // 不包括不常用的 symbol 和 bigint
  4. export type Primitive = string | number | boolean | undefined;
  5. export const isPrimitive = (val: unknown): val is Primitive => ['string', 'number', 'boolean' , 'undefined'].includes(typeof val);

基于 in 与 instanceof 的类型保护

in操作符 并不是 TypeScript 中新增的概念,而是 JavaScript 中已有的部分,它可以通过 key in object 的方式来判断 key 是否存在于 object 或其原型链上(返回 true 说明存在)。
既然能起到区分作用,那么 TypeScript 中自然也可以用它来保护类型:

  1. interface Foo {
  2. foo: string;
  3. fooOnly: boolean;
  4. shared: number;
  5. }
  6. interface Bar {
  7. bar: string;
  8. barOnly: boolean;
  9. shared: number;
  10. }
  11. function handle(input: Foo | Bar) {
  12. if ('foo' in input) {
  13. input.fooOnly;
  14. } else {
  15. input.barOnly;
  16. }
  17. }

这里的 foo / bar、fooOnly / barOnly、shared 属性们其实有着不同的意义。我们使用 foo 和 bar 来区分 input 联合类型,然后就可以在对应的分支代码块中正确访问到 Foo 和 Bar 独有的类型 fooOnly / barOnly。但是,如果用 shared 来区分,就会发现在分支代码块中 input 仍然是初始的联合类型:

  1. function handle(input: Foo | Bar) {
  2. if ('shared' in input) {
  3. // 类型“Foo | Bar”上不存在属性“fooOnly”。类型“Bar”上不存在属性“fooOnly”。
  4. input.fooOnly;
  5. } else {
  6. // 类型“never”上不存在属性“barOnly”。
  7. input.barOnly;
  8. }
  9. }

这里需要注意的是,Foo 与 Bar 都满足 ‘shared’ in input 这个条件。因此在 if 分支中, Foo 与 Bar 都会被保留,那在 else 分支中就只剩下 never 类型。

这个时候肯定有人想问,为什么 shared 不能用来区分?答案很明显,因为它同时存在两个类型中不具有辨识度。而 foo / bar 和 fooOnly / barOnly 是各个类型独有的属性,因此可以作为可辨识属性(Discriminant Property 或 Tagged Property)。Foo 与 Bar 又因为存在这样具有区分能力的辨识属性,可以称为可辨识联合类型(Discriminated Unions 或 Tagged Union)。虽然它们是一堆类型的联合体,但其中每一个类型都具有一个独一无二的,能让它鹤立鸡群的属性。

这个可辨识属性可以是结构层面的,比如结构 A 的属性 prop 是数组,而结构 B 的属性 prop 是对象,或者结构 A 中存在属性 prop 而结构 B 中不存在。
它甚至可以是共同属性的字面量类型差异:

  1. function ensureArray(input: number | number[]): number[] {
  2. if (Array.isArray(input)) {
  3. return input;
  4. } else {
  5. return [input];
  6. }
  7. }
  8. interface Foo {
  9. kind: 'foo';
  10. diffType: string;
  11. fooOnly: boolean;
  12. shared: number;
  13. }
  14. interface Bar {
  15. kind: 'bar';
  16. diffType: number;
  17. barOnly: boolean;
  18. shared: number;
  19. }
  20. function handle1(input: Foo | Bar) {
  21. if (input.kind === 'foo') {
  22. input.fooOnly;
  23. } else {
  24. input.barOnly;
  25. }
  26. }


如上例所示,对于同名但不同类型的属性,我们需要使用字面量类型的区分,并不能使用简单的 typeof:

  1. function handle2(input: Foo | Bar) {
  2. // 报错,并没有起到区分的作用,在两个代码块中都是 Foo | Bar
  3. if (typeof input.diffType === 'string') {
  4. input.fooOnly;
  5. } else {
  6. input.barOnly;
  7. }
  8. }

除此之外,JavaScript 中还存在一个功能类似于 typeof 与 in 的操作符:instanceof,它判断的是原型级别的关系,如 foo instanceof Base 会沿着 foo 的原型链查找 Base.prototype 是否存在其上。当然,在 ES6 已经无处不在的今天,我们也可以简单地认为这是判断 foo 是否是 Base 类的实例。同样的,instanceof 也可以用来进行类型保护:

  1. class FooBase {}
  2. class BarBase {}
  3. class Foo extends FooBase {
  4. fooOnly() {}
  5. }
  6. class Bar extends BarBase {
  7. barOnly() {}
  8. }
  9. function handle(input: Foo | Bar) {
  10. if (input instanceof FooBase) {
  11. input.fooOnly();
  12. } else {
  13. input.barOnly();
  14. }
  15. }

除了使用 is 关键字的类型守卫以外,其实还存在使用 asserts 关键字的类型断言守卫。

类型断言守卫

如果你写过测试用例或者使用过 NodeJs 的 assert 模块,那对断言这个概念应该不陌生:

  1. import assert from 'assert';
  2. let name: any = 'linbudu';
  3. assert(typeof name === 'number');
  4. // number 类型
  5. name.toFixed();

上面这段代码在运行时会抛出一个错误,因为 assert 接收到的表达式执行结果为 false。这其实也类似类型守卫的场景:如果断言不成立,比如在这里意味着值的类型不为 number,那么在断言下方的代码就执行不到(相当于 Dead Code)。如果断言通过了,不管你最开始是什么类型,断言后的代码中就一定是符合断言的类型,比如在这里就是 number。

但断言守卫和类型守卫最大的不同点在于,在判断条件不通过时,断言守卫需要抛出一个错误,类型守卫只需要剔除掉预期的类型。 这里的抛出错误可能让你想到了 never 类型,但实际情况要更复杂一些,断言守卫并不会始终都抛出错误,所以它的返回值类型并不能简单地使用 never 类型。为此,TypeScript 3.7 版本专门引入了 asserts 关键字来进行断言场景下的类型守卫,比如前面 assert 方法的签名可以是这样的:

  1. function assert(condition: any, msg?: string): asserts condition {
  2. if (!condition) {
  3. throw new Error(msg);
  4. }
  5. }

这里使用的是 asserts condition ,而 condition 来自于实际逻辑!这也意味着,我们将 condition 这一逻辑层面的代码,作为了类型层面的判断依据,相当于在返回值类型中使用一个逻辑表达式进行了类型标注。
举例来说,对于 assert(typeof name === ‘number’); 这么一个断言,如果函数成功返回,就说明其后续的代码中 condition 均成立,也就是 name 神奇地变成了一个 number 类型。
这里的 condition 甚至还可以结合使用 is 关键字来提供进一步的类型守卫能力:

  1. let name: any = 'linbudu';
  2. function assertIsNumber(val: any): asserts val is number {
  3. if (typeof val !== 'number') {
  4. throw new Error('Not a number!');
  5. }
  6. }
  7. assertIsNumber(name);
  8. // number 类型!
  9. name.toFixed();

在这种情况下,你无需再为断言守卫传入一个表达式,而是可以将这个判断用的表达式放进断言守卫的内部,来获得更独立地代码逻辑。