1. 交叉类型
  2. 联合类型
  3. 类型保护
  4. 可以为 null 的类型
  5. 字符串字面量类型

1. 交叉类型

交叉类型是将多个类型合并为一个类型。 这让我们可以把现有的多种类型叠加到一起成为一种类型,它包含了所需的所有类型的特性。 例如,Person & Serializable & Loggable 同时是 PersonSerializableLoggable。 此时这个类型的对象同时拥有了这三种类型的成员。

2. 联合类型

联合类型表示一个值可以是几种类型之一。 我们用竖线(|)分隔每个类型,所以 number | string | boolean 表示一个值可以是 numberstring,或 boolean

如果一个值是联合类型,与交叉类型不同的是,我们只能访问此联合类型的所有类型里共有的成员。

  1. interface Bird {
  2. fly();
  3. layEggs();
  4. }
  5. interface Fish {
  6. swim();
  7. layEggs();
  8. }
  9. function getSmallPet(): Fish | Bird {
  10. // ...
  11. }
  12. let pet = getSmallPet();
  13. pet.layEggs(); // ok
  14. pet.swim(); // 报错,无法推断出

3. 类型保护

刚才也说了,TS 会对类型进行检查、推断,当尝试访问一个成员时,TS 会检查是否符合类型推论。接着上面的例子,JS 中一般会这样写判断,为了保证能读取到拥有的属性,但在 if 的时候 TS 就会给出报错,因为只能访问联合类型中的共同拥有的成员:

  1. let pet = getSmallPet();
  2. // 每一个成员访问都会报错
  3. if (pet.swim) {
  4. pet.swim();
  5. }
  6. else if (pet.fly) {
  7. pet.fly();
  8. }

为了符合类型检查,可以使用类型断言,但这样的代码看起来实在是反而被 TS 拖累:

  1. let pet = getSmallPet();
  2. if ((<Fish>pet).swim) { // 类型断言可以这样写
  3. (<Fish>pet).swim();
  4. } else {
  5. (pet as Bird).fly(); // 类型断言也可以这样写,比较推荐这种写法
  6. }

3.1 用户自定义类型保护

TS 里的类型保护机制是一些表达式,会在运行时检查以确保某个作用域里的类型,针对刚才的啰嗦例子,可以定义一个函数,用作类型保护,返回值是一个类型谓词:

  1. function isFish(pet: Fish | Bird): pet is Fish {
  2. return (pet as Fish).swim !== undefined;
  3. }

现在 TS 知道 if 分支里的 petFish 类型,而且还能推断出 else 分支里一定是 Bird 类型:

  1. if (isFish(pet)) {
  2. pet.swim();
  3. } else {
  4. pet.fly();
  5. }

3.2 typeof 类型保护

判断类型是否是某个原始类型,会使用到 typeof,TS 可以将其识别为一种类型保护。这些 typeof 类型保护只有两种形式能被识别:
typeof v === "typename"typeof v !== "typename""typename" 必须是 "number""string""boolean""symbol"。 也就是说只有判断原始类型的时候,才会触发 typeof 类型保护。

所谓保护,就是判断之后的局部作用域中,会得到 TS 的认可,认为是安全的,不再需要人工去做类型断言:

  1. function padLeft(value: string, padding: string | number) {
  2. if (typeof padding === "number") {
  3. return Array(padding + 1).join(" ") + value;
  4. }
  5. if (typeof padding === "string") {
  6. return padding + value;
  7. }
  8. throw new Error(`Expected string or number, got '${padding}'.`);
  9. }

3.3 instanceof 类型保护

类似于 typeof 类型保护,经过 instanceof 判断后,在局部作用域中,相关实例的类型就会被 TS 认可为右边的类型:

  1. class Bird {
  2. fly() {
  3. console.log('bird fly');
  4. };
  5. layEggs() {
  6. console.log('bird lay eggs');
  7. };
  8. }
  9. class Fish {
  10. swim() {
  11. console.log('fish swim');
  12. };
  13. layEggs() {
  14. console.log('fish lay eggs');
  15. };
  16. }
  17. function getRandomPet(): Fish | Bird {
  18. return Math.random() > 0.5 ? new Fish() : new Bird();
  19. }
  20. let pet = getRandomPet();
  21. if (pet instanceof Bird) {
  22. pet.fly();
  23. } else {
  24. pet.swim();
  25. }

4. 可以为 null 的类型

nullundefined 既可以作为类型,又可以做为值,默认情况下,可以赋值给任何类型,编译时添加 --strictNullChecks 标记可以解决此错误,此时声明变量时不再自动包含 nullundefined,可以使用联合类型明确的包含它们:

  1. let s = "foo";
  2. s = null; // 错误, 'null'不能赋值给'string'
  3. let sn: string | null = "bar";
  4. sn = null; // 可以
  5. sn = undefined; // error, 'undefined'不能赋值给'string | null'

4.1 可选参数和可选属性

使用了--strictNullChecks,可选参数会被自动地加上 `| undefined:

  1. function f(x: number, y?: number) {
  2. return x + (y || 0);
  3. }
  4. f(1, 2); // ok
  5. f(1); // ok
  6. f(1, undefined); // ok
  7. f(1, null); // 报错,Argument of type 'null' is not assignable to parameter of type 'number | undefined'.

可选属性同理:

  1. class C {
  2. a: number;
  3. b?: number;
  4. }
  5. let c = new C();
  6. c.a = 12; // ok
  7. c.a = undefined; // 报错,因为 a 要求的类型是 number,虽然使用了 --strictNullChecks,但 a 并不是可选参数,不会自动添加 | undefined
  8. c.b = 13; // ok
  9. c.b = undefined; // ok,因为使用了--strictNullChecks,可选参数会被自动地加上 | undefined
  10. c.b = null; // 报错,Argument of type 'null' is not assignable to parameter of type 'number | undefined'.

4.2 类型保护和类型断言

前面介绍了用户自定义类型保护、typeof 类型保护、instanceof 类型保护,而 TS 中关于排除 null 的类型保护和 JS 中写法一致:

  1. function foo(name: string | null): string {
  2. if (name == null) {
  3. return 'Tony';
  4. } else {
  5. return name;
  6. }
  7. }

也可以使用短路运算符:

  1. function foo(name: string | null): string {
  2. return name || 'Tony';
  3. }

但是编译器无法去除嵌套函数的 null,除非是立即调用的函数表达式,因为内层函数可能会作为外层的返回值将来在别的地方被调用,编译器无法跟踪。

此时可以使用类型断言手动去除,只需要在变量后面添加 ! 后缀,就能从该变量类型中去除 nullundefined

  1. function bar(name: string | null): string {
  2. function postfix(nickname: string) {
  3. return name!.charAt(0) + '_' + nickname;
  4. }
  5. name = name || 'Tom';
  6. return postfix('sweet');
  7. }

5. 字符串字面量类型

字符串字面量类型允许你指定字符串必须的固定值,如下所示,只能从三种允许的字符串中选择其一来做为参数传递,传入其它值会报错:

  1. type Easing = "ease-in" | "ease-out" | "ease-in-out";
  2. class UIElement {
  3. animate(dx: number, dy: number, easing: Easing) {
  4. if (easing === "ease-in") {
  5. // ...
  6. }
  7. else if (easing === "ease-out") {
  8. }
  9. else if (easing === "ease-in-out") {
  10. }
  11. else {
  12. // error! should not pass null or undefined.
  13. }
  14. }
  15. }
  16. let button = new UIElement();
  17. button.animate(0, 0, "ease-in");
  18. button.animate(0, 0, "uneasy"); // 报错,Argument of type '"uneasy"' is not assignable to parameter of type 'Easing'.ts(2345)

后记

TypeScript 文档的学习,就先告一段落了,虽然还有一些知识点没有提到,但目前涉及的这些能满足大部分的场景,接下来还需要实战。