高级类型·续1

function broken(name: string | null): string {  function postfix(epithet: string) {    return name.charAt(0) + '.  the ' + epithet; // error, 'name' is possibly null  }  name = name || "Bob";  return postfix("great");}function fixed(name: string | null): string {  function postfix(epithet: string) {    return name!.charAt(0) + '.  the ' + epithet; // ok  }  name = name || "Bob";  return postfix("great");}

本例使用了嵌套函数,因为编译器无法去除嵌套函数的null(除非是立即调用的函数表达式)。 因为它无法跟踪所有对嵌套函数的调用,尤其是你将内层函数做为外层函数的返回值。 如果无法知道函数在哪里被调用,就无法知道调用时name的类型。

类型别名

类型别名会给一个类型起个新名字。 类型别名有时和接口很像,但是可以作用于原始值,联合类型,元组以及其它任何你需要手写的类型。

type Name = string;type NameResolver = () => string;type NameOrResolver = Name | NameResolver;function getName(n: NameOrResolver): Name {    if (typeof n === 'string') {        return n;    }    else {        return n();    }}

起别名不会新建一个类型 - 它创建了一个新名字来引用那个类型。 给原始类型起别名通常没什么用,尽管可以做为文档的一种形式使用。

同接口一样,类型别名也可以是泛型 - 我们可以添加类型参数并且在别名声明的右侧传入:

type Container<​T> = { value: T };

我们也可以使用类型别名来在属性里引用自己:

type Tree<​T> = {    value: T;    left: Tree<​T>;    right: Tree<​T>;}

与交叉类型一起使用,我们可以创建出一些十分稀奇古怪的类型。

type LinkedList<​T> = T & { next: LinkedList<​T> };interface Person {    name: string;}var people: LinkedList<​Person>;var s = people.name;var s = people.next.name;var s = people.next.next.name;var s = people.next.next.next.name;

然而,类型别名不能出现在声明右侧的任何地方。

type Yikes = Array<​Yikes>; // error

接口 vs. 类型别名

像我们提到的,类型别名可以像接口一样;然而,仍有一些细微差别。

其一,接口创建了一个新的名字,可以在其它任何地方使用。 类型别名并不创建新名字—比如,错误信息就不会使用别名。 在下面的示例代码里,在编译器中将鼠标悬停在interfaced上,显示它返回的是Interface,但悬停在aliased上时,显示的却是对象字面量类型。

type Alias = { num: number }interface Interface {    num: number;}declare function aliased(arg: Alias): Alias;declare function interfaced(arg: Interface): Interface;

在旧版本的TypeScript里,类型别名不能被继承和实现(它们也不能继承和实现其它类型)。从TypeScript 2.7开始,类型别名可以被继承并生成新的交叉类型。例如:type Cat = Animal & { purrs: true }。

因为软件中的对象应该对于扩展是开放的,但是对于修改是封闭的,你应该尽量去使用接口代替类型别名。

另一方面,如果你无法通过接口来描述一个类型并且需要使用联合类型或元组类型,这时通常会使用类型别名。

字符串字面量类型

字符串字面量类型允许你指定字符串必须的固定值。 在实际应用中,字符串字面量类型可以与联合类型,类型守卫和类型别名很好的配合。 通过结合使用这些特性,你可以实现类似枚举类型的字符串。

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"); // error: "uneasy" is not allowed here

你只能从三种允许的字符中选择其一来做为参数传递,传入其它值则会产生错误。

Argument of type '"uneasy"' is not assignable to parameter of type '"ease-in" | "ease-out" | "ease-in-out"'

字符串字面量类型还可以用于区分函数重载:

function createElement(tagName: "img"): HTMLImageElement;function createElement(tagName: "input"): HTMLInputElement;// ... more overloads ...function createElement(tagName: string): Element {    // ... code goes here ...}

数字字面量类型

TypeScript还具有数字字面量类型。

function rollDice(): 1 | 2 | 3 | 4 | 5 | 6 {    // ...}

我们很少直接这样使用,但它们可以用在缩小范围调试bug的时候:

function foo(x: number) {    if (x !== 1 || x !== 2) {        //         ~~~~~~~        // Operator '!==' cannot be applied to types '1' and '2'.    }}

换句话说,当x与2进行比较的时候,它的值必须为1,这就意味着上面的比较检查是非法的。

枚举成员类型

如我们在枚举一节里提到的,当每个枚举成员都是用字面量初始化的时候枚举成员是具有类型的。

在我们谈及“单例类型”的时候,多数是指枚举成员类型和数字/字符串字面量类型,尽管大多数用户会互换使用“单例类型”和“字面量类型”。

可辨识联合(Discriminated Unions)

你可以合并单例类型,联合类型,类型守卫和类型别名来创建一个叫做可辨识联合的高级模式,它也称做标签联合或代数数据类型。 可辨识联合在函数式编程里很有用处。 一些语言会自动地为你辨识联合;而TypeScript则基于已有的JavaScript模式。 它具有3个要素:

  • 具有普通的单例类型属性—可辨识的特征。

  • 一个类型别名包含了那些类型的联合—联合。

  • 此属性上的类型守卫。

interface Square {    kind: "square";    size: number;}interface Rectangle {    kind: "rectangle";    width: number;    height: number;}interface Circle {    kind: "circle";    radius: number;}

首先我们声明了将要联合的接口。 每个接口都有kind属性但有不同的字符串字面量类型。 kind属性称做可辨识的特征或标签。 其它的属性则特定于各个接口。 注意,目前各个接口间是没有联系的。 下面我们把它们联合到一起:

type Shape = Square | Rectangle | Circle;

现在我们使用可辨识联合:

function area(s: Shape) {    switch (s.kind) {        case "square": return s.size * s.size;        case "rectangle": return s.height * s.width;        case "circle": return Math.PI * s.radius ** 2;    }}

完整性检查

当没有涵盖所有可辨识联合的变化时,我们想让编译器可以通知我们。 比如,如果我们添加了Triangle到Shape,我们同时还需要更新area:

type Shape = Square | Rectangle | Circle | Triangle;function area(s: Shape) {    switch (s.kind) {        case "square": return s.size * s.size;        case "rectangle": return s.height * s.width;        case "circle": return Math.PI * s.radius ** 2;    }    // should error here - we didn't handle case "triangle"}

有两种方式可以实现。 首先是启用--strictNullChecks并且指定一个返回值类型:

function area(s: Shape): number { // error: returns number | undefined    switch (s.kind) {        case "square": return s.size * s.size;        case "rectangle": return s.height * s.width;        case "circle": return Math.PI * s.radius ** 2;    }}

因为switch没有包含所有情况,所以TypeScript认为这个函数有时候会返回undefined。 如果你明确地指定了返回值类型为number,那么你会看到一个错误,因为实际上返回值的类型为number | undefined。 然而,这种方法存在些微妙之处且--strictNullChecks对旧代码支持不好。

第二种方法使用never类型,编译器用它来进行完整性检查:

function assertNever(x: never): never {    throw new Error("Unexpected object: " + x);}function area(s: Shape) {    switch (s.kind) {        case "square": return s.size * s.size;        case "rectangle": return s.height * s.width;        case "circle": return Math.PI * s.radius ** 2;        default: return assertNever(s); // error here if there are missing cases    }}

这里,assertNever检查s是否为never类型—即为除去所有可能情况后剩下的类型。 如果你忘记了某个case,那么s将具有一个真实的类型并且你会得到一个错误。 这种方式需要你定义一个额外的函数,但是在你忘记某个case的时候也更加明显。

多态的this类型

多态的this类型表示的是某个包含类或接口的子类型。 这被称做F-bounded多态性。 它能很容易的表现连贯接口间的继承,比如。 在计算器的例子里,在每个操作之后都返回this类型:

class BasicCalculator {    public constructor(protected value: number = 0) { }    public currentValue(): number {        return this.value;    }    public add(operand: number): this {        this.value += operand;        return this;    }    public multiply(operand: number): this {        this.value *= operand;        return this;    }    // ... other operations go here ...}let v = new BasicCalculator(2)            .multiply(5)            .add(1)            .currentValue();

由于这个类使用了this类型,你可以继承它,新的类可以直接使用之前的方法,不需要做任何的改变。

class ScientificCalculator extends BasicCalculator {    public constructor(value = 0) {        super(value);    }    public sin() {        this.value = Math.sin(this.value);        return this;    }    // ... other operations go here ...}let v = new ScientificCalculator(2)        .multiply(5)        .sin()        .add(1)        .currentValue();

如果没有this类型,ScientificCalculator就不能够在继承BasicCalculator的同时还保持接口的连贯性。 multiply将会返回BasicCalculator,它并没有sin方法。 然而,使用this类型,multiply会返回this,在这里就是ScientificCalculator。

索引类型(Index types)

使用索引类型,编译器就能够检查使用了动态属性名的代码。 例如,一个常见的JavaScript模式是从对象中选取属性的子集。

function pluck(o, propertyNames) {    return propertyNames.map(n => o[n]);}

下面是如何在TypeScript里使用此函数,通过索引类型查询和索引访问操作符:

function pluck<​T, K extends keyof T>(o: T, propertyNames: K[]): T[K][] {  return propertyNames.map(n => o[n]);}interface Car {    manufacturer: string;    model: string;    year: number;}let taxi: Car = {    manufacturer: 'Toyota',    model: 'Camry',    year: 2014};// Manufacturer and model are both of type string,// so we can pluck them both into a typed string arraylet makeAndModel: string[] = pluck(taxi, ['manufacturer', 'model']);// If we try to pluck model and year, we get an// array of a union type: (string | number)[]let modelYear = pluck(taxi, ['model', 'year'])

编译器会检查manufacturer和model是否真的是Car上的一个属性。 本例还引入了几个新的类型操作符。 首先是keyof T,索引类型查询操作符。 对于任何类型T,keyof T的结果为T上已知的公共属性名的联合。 例如:

let carProps: keyof Car; // the union of ('manufacturer' | 'model' | 'year')