TypeScript 文档学习

TypeScript 08 - 高级类型

2019-12-01  本文已影响0人  晓风残月1994
  1. 交叉类型
  2. 联合类型
  3. 类型保护
  4. 可以为 null 的类型
  5. 字符串字面量类型

1. 交叉类型

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

2. 联合类型

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

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

interface Bird {
    fly();
    layEggs();
}

interface Fish {
    swim();
    layEggs();
}

function getSmallPet(): Fish | Bird {
    // ...
}

let pet = getSmallPet();
pet.layEggs(); // ok
pet.swim();    // 报错,无法推断出

3. 类型保护

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

let pet = getSmallPet();

// 每一个成员访问都会报错
if (pet.swim) {
    pet.swim();
}
else if (pet.fly) {
    pet.fly();
}

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

let pet = getSmallPet();

if ((<Fish>pet).swim) { // 类型断言可以这样写
  (<Fish>pet).swim();
} else {
  (pet as Bird).fly(); // 类型断言也可以这样写,比较推荐这种写法
}

3.1 用户自定义类型保护

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

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

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

if (isFish(pet)) {
  pet.swim();
} else {
  pet.fly();
}

3.2 typeof 类型保护

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

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

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

3.3 instanceof 类型保护

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

class Bird {
  fly() {
    console.log('bird fly');
  };

  layEggs() {
    console.log('bird lay eggs');
  };
}

class Fish {
  swim() {
    console.log('fish swim');
  };

  layEggs() {
    console.log('fish lay eggs');
  };
}

function getRandomPet(): Fish | Bird {
  return Math.random() > 0.5 ? new Fish() : new Bird();
}

let pet = getRandomPet();

if (pet instanceof Bird) {
  pet.fly();
} else {
  pet.swim();
}

4. 可以为 null 的类型

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

let s = "foo";
s = null; // 错误, 'null'不能赋值给'string'
let sn: string | null = "bar";
sn = null; // 可以

sn = undefined; // error, 'undefined'不能赋值给'string | null'

4.1 可选参数和可选属性

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

function f(x: number, y?: number) {
  return x + (y || 0);
}

f(1, 2); // ok
f(1); // ok
f(1, undefined); // ok

f(1, null); // 报错,Argument of type 'null' is not assignable to parameter of type 'number | undefined'.

可选属性同理:

class C {
  a: number;
  b?: number;
}

let c = new C();

c.a = 12; // ok
c.a = undefined; // 报错,因为 a 要求的类型是 number,虽然使用了 --strictNullChecks,但 a 并不是可选参数,不会自动添加 | undefined
c.b = 13; // ok
c.b = undefined; // ok,因为使用了--strictNullChecks,可选参数会被自动地加上 | undefined
c.b = null; // 报错,Argument of type 'null' is not assignable to parameter of type 'number | undefined'.

4.2 类型保护和类型断言

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

function foo(name: string | null): string {
  if (name == null) {
    return 'Tony';
  } else {
    return name;
  }
}

也可以使用短路运算符:

function foo(name: string | null): string {
  return name || 'Tony';
}

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

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

function bar(name: string | null): string {
  function postfix(nickname: string) {
    return name!.charAt(0) + '_' + nickname;
  }
  name = name || 'Tom';
  return postfix('sweet');
}

5. 字符串字面量类型

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

type Easing = "ease-in" | "ease-out" | "ease-in-out";
class UIElement {
    animate(dx: number, dy: number, easing: Easing) {
        if (easing === "ease-in") {
            // ...
        }
        else if (easing === "ease-out") {
        }
        else if (easing === "ease-in-out") {
        }
        else {
            // error! should not pass null or undefined.
        }
    }
}

let button = new UIElement();
button.animate(0, 0, "ease-in");
button.animate(0, 0, "uneasy"); // 报错,Argument of type '"uneasy"' is not assignable to parameter of type 'Easing'.ts(2345)

后记

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

上一篇 下一篇

猜你喜欢

热点阅读