在上一章节中,我们介绍了 TypeScript 的泛型,在这个章节我们会继续介绍更多态别的应用。
类型的联集(union)运算
我们在先前的章节中,有在类型中使用 | 字符来连接两个不同的类型。例如 A | B,表示这个类型的值可以为 A 类型或是 B 类型。
然而事实上,| 字符并不是那么单纯的东西。先看看以下这个例子:
const o1: { a: number } = { a: 1, b: "2" };
const o2: { b: string } = { a: 1, b: "2" };
以上的两个程序叙述都会编译失败,因为 {a: 1, b: "2"} 的类型为 {a: number, b: string},所以若要让以上程序能够通过编译,就必须要用如下的方式来转型:
const o = { a: 1, b: "2" };
const o1: { a: number } = o;
const o2: { b: string } = { a: 1, b: "2" } as { b: string };
以上程序中,o2 变量那行使用了 as 关键字来转型,这看起来没什么问题。但是 o1 变量那边只是把原来的 {a: 1, b: "2"} 对象事先存到 o 变量中,为什么拆开来写就可以编译了?这应该是 TypeScript 怕开发者在首次明确定义大括号对象的类型时,不小心没写到对象中有用到的属性才做的限制吧!
顺带一提,数组也存在着类似的限制,但数组必须要使用 as 来强制转型才能够忽略不想使用的元素。以下例子看看就好,很少看到有人这样用:
const a = [1, "2", false];
const a1: [number, string] = a; // compilation Error
const a2: [number, string] = a as [number, string];
回到对象上,基于这个限制,如果我们将以下程序的 o1 变量和 o2 变量的类型用 | 组合在一起,
const o1: { a: number } = { a: 1, b: "2" };
const o2: { b: string } = { a: 1, b: "2" };
使其变为:
const o: { a: number } | { b: string } = { a: 1, b: "2" };
理论上以上这个程序应该也是不能成功编译才对。但实际上,它是可以通过编译的!
而以上的变量 o 需要透过转型才可以访问其 a、b 属性。例如:
const o: { a: number } | { b: string } = { a: 1, b: "2" };
const oa = o as { a: number };
console.log(oa.a);
const ob = o as { b: string };
console.log(ob.b);
所以我们可以看出在类型中使用 | 字符,并不只是单纯用来列出「值可能的类型」,它还有一点联集(如 { a: number } | { b: string } 像是被合并为 { a: number, b?: string } | { a?: number, b: string }),又或者说「列出来的类型中,要有至少一个是值可以直接转型过去的类型」的概念存在。
类型的交集(intersection)运算
类型中除了能使用 | 字符来连接两个不同的类型外,还可以用 & 字符来连接两个不同的类型。& 字符有一点交集(如 { a: number } & { b: string } 像是被合并为 { a: number, b: string }),又或者说「列出来的类型,全部都必须是值可以直接转型过去的类型」的概念存在。
例如:
const o: { a: number } & { b: string } = { a: 1, b: "2" };
console.log(o.a);
console.log(o.b);
类型的群组
利用小括号 (),可以将括号内的类型当作一个群组。
例如,若我们想要定义一个数值或是字符串的数组类型,如果写成以下这样的话就会有问题:
const a: string | number[] = ["I am a string."];
正确的写法应为:
const a: string[] | number[] = ["I am a string."];
或是利用小括号 (),将 string | number 括起来当作群组。
const a: (string | number)[] = ["I am a string."];
类型的别名
使用 type 关键字可以替一个类型定义出一个新别名,方便重复使用。
例如:
type A = { a: number };
type B = { b: string };
type AB = A | B;
const o: AB = { a: 1, b: "2" };
const oa = o as A;
console.log(oa.a);
const ob = o as B;
console.log(ob.b);
别名也可以使用泛型。例如:
type MyType<T> = T | undefined;
类型的条件运算
类型中可以配合 extends 关键字来使用三元条件操作符,判断一个类型是否属于另一个类型的子类型(或者两个类型相等)。
例如:
type A<T, K> = T extends K ? number : string;
以上这个 A 类型,若 T 泛型参数实际的类型不是 K 泛型参数实际的类型或是其子类型,则这个 A 类型就是 string;反之就是 number。
用来做类型运算的 TypeScript 内置类型
除了刚才介绍的 &、|、小括号 ()、extends 关键字与三元条件操作符可以做类型运算之外,TypeScript 还内置了以下几种常用的类型。
Exclude
Exclude 定义如下:
type Exclude<T, U> = T extends U ? never : T;
说明:T 必须不能是 U 或 U 的子类型。
Extract
Extract 定义如下:
type Extract<T, U> = T extends U ? T : never;
说明:T 必须要是 U 或 U 的子类型。
NonNullable
NonNullable 定义如下:
type NonNullable<T> = T extends null | undefined ? never : T;
说明:T 必须不可以为 null 或 undefined。
ReturnType
ReturnType 定义如下:
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;
注意这边的函数回传值类型用到了 infer 关键字,表示要让 TypeScript 根据函数实际用 return 关键字回传出来的值(如果没有用的话就是 void),来推论 R 这个泛型参数实际代表的类型。infer 关键字一定要用在 extends 关键字所组成的三元条件操作符的第一个操作数中。
说明:T 必须要是一个函数,且 ReturnType<T> 为这个函数的回传值类型。
InstanceType
InstanceType 定义如下:
type InstanceType<T extends new (...args: any) => any> = T extends new (...args: any) => infer R ? R : any;
说明:T 必须要是一个函数或是类别,且 InstanceType<T> 为这个函数或是类别被使用 new 关键字后所创建出来的对象实体的类型。
拷贝值的类型
前面的章节有介绍过使用 typeof 关键字来取得某表达式的回传值的类型。在类型中,我们也可以使用 typeof 关键字来取得值的类型。换句话说,可以「拷贝」这个值的类型,用在其它地方。
例如:
let foo = 123;
let bar: typeof foo;
以上程序,foo 变量的类型为 number,而 bar 变量的类型被明确定义为 typeof foo,表示要使用 foo 变量的类型,也就是 number。
当 typeof 关键字用在类型上时,其后只能够接上有在 TypeScript 程序中被定义的名称或是路径,无法直接使用定数或是表达式。
再举一个例子:
class Foo {
foo = 0;
}
declare let _foo: Foo;
let bar: typeof _foo.foo;
以上程序,没有实际产生 Foo 类别的对象,而是使用 declare 关键字假声明了一个类型为 Foo 的 _foo 变量,并在程序第 7 行利用 typeof 关键字来取得 Foo 类别的 foo 对象属性的类型,也就是 number。
有个蛮容易会被雷到的地方要提一下,前面的章节有介绍过定数类型,常数的值若是基本数据类型的值,则常数的类型会被推论为这个值的定数。所以当 typeof 关键字后面接的是一个常数时,就要注意一下这样的程序逻辑是不是真的是我们要的。
举例来说:
const foo = "Hello World";
let bar: typeof foo;
bar = "Hello World";
bar = "something else"; // compilation Error
以上程序,第 6 行会编译失败,因为 bar 的类型为 "Hello World"。
拷贝键值的类型
除了值的类型能够被拷贝之外,对象的键值的类型也是可以拷贝的。
若要拷贝对象的键值,只要在 typeof 关键字前再加上 keyof 关键字就好。
举例来说:
class F {
readonly name: string;
readonly age: number;
readonly studentNumber?: string;
constructor(name: string, age: number, studentNumber?: string) {
this.name = name;
this.age = age;
this.studentNumber = studentNumber;
}
toString() {
return `${this.name}: ${this.age}`;
}
}
const o = new F("David", 18);
type FKey = keyof typeof o;
let key: FKey;
key = "name";
key = "age";
key = "studentNumber";
key = "toString";
以上程序,FKey 这个类型其实就是 "name" | "age" | "studentNumber" | "toString",所以类型为 FKey 的 key 变量可以避免使用到超出 F 类别定义的属性名称。
可惜的是,如果对象是数组的话,我们没有办法利用这个方式来限制该数组能够访问的索引值范围,因为数组的索引值范围就是整个 number 类型的值。举例来说:
const o = [1, 3, 5, 7];
let key: keyof typeof o;
key = "length";
key = 1;
key = 2;
key = 3;
key = 4;
虽然我们知道以上的 o 数组并不存在索引值 4,但程序第 9 行还是可以通过编译。
指定 Node.js 的 require 函数回传的类型
由于 Node.js 内置的 require 函数是在程序运行阶段动态加载指定的模块,因此尽管有 Node.js 的 .d.ts 定义文件,TypeScript 在编译阶段依然无法得知 require 函数确切的回传值类型,只能先将其以 any 来看待。
以前面的章节写过的猜数字程序来说明,代码如下:
const isBrowser: boolean = typeof window === "object";
function showMessage(text: string): void {
if (isBrowser) {
alert(text);
} else {
console.log(text);
}
}
async function showMessageAndInputText(text: string): Promise<string | null> {
if (isBrowser) {
return prompt(text);
} else {
console.log(text);
const readline = require("node:readline");
const rl = readline.createInterface({ input: process.stdin });
const lineResolver: Promise<string> = new Promise<string>(resolve => {
rl.on("line", (line: string) => resolve(line));
});
const line: string = await lineResolver;
rl.close();
return line;
}
}
async function main(): Promise<void> {
showMessage("Guess the number!");
const secretNumber: number = Math.floor(Math.random() * 100 + 1);
showMessage(`The secret number is: ${secretNumber}`);
while (true) {
const line: string | null = await showMessageAndInputText("Please input your guess.");
if (line === null) {
continue;
}
const guess: number = parseInt(line);
if (isNaN(guess)) {
showMessage("Please type a number!");
} else {
showMessage(`You guessed: ${guess}`);
if (guess < secretNumber) {
showMessage("Too small!");
} else if (guess > secretNumber) {
showMessage("Too big!");
} else {
showMessage("You win!");
break;
}
}
}
}
main();
以上程序第 17 行,使用 require 函数来加载 readline 模块,此时的 readline 变量的类型为 any,这很显然地会让我们无法好好地应用 TypeScript 的类型检查机制。
为了让 TypeScript 能够认识模块的类型,我们可以在程序最外层,使用 import 关键字来声明出一个自定义的模块名称,来表示一个模块。例如:
import readline = require("node:readline");
const isBrowser: boolean = typeof window === "object";
function showMessage(text: string): void {
if (isBrowser) {
alert(text);
} else {
console.log(text);
}
}
async function showMessageAndInputText(text: string): Promise<string | null> {
if (isBrowser) {
return prompt(text);
} else {
console.log(text);
// const readline = require('node:readline');
const rl = readline.createInterface({ input: process.stdin });
const lineResolver: Promise<string> = new Promise<string>(resolve => {
rl.on("line", (line) => resolve(line));
});
const line: string = await lineResolver;
rl.close();
return line;
}
}
async function main(): Promise<void> {
showMessage("Guess the number!");
const secretNumber: number = Math.floor(Math.random() * 100 + 1);
showMessage(`The secret number is: ${secretNumber}`);
while (true) {
const line: string | null = await showMessageAndInputText("Please input your guess.");
if (line === null) {
continue;
}
const guess: number = parseInt(line);
if (isNaN(guess)) {
showMessage("Please type a number!");
} else {
showMessage(`You guessed: ${guess}`);
if (guess < secretNumber) {
showMessage("Too small!");
} else if (guess > secretNumber) {
showMessage("Too big!");
} else {
showMessage("You win!");
break;
}
}
}
}
main();
透过 import 关键字和 require 函数的搭配使用,此时的我们自定义的模块名称 readline 就有了正确的类型定义。但是别忘了,我们的猜数字程序必须也要能运行在网页浏览器上,以上这样的写法编译出来的 JavaScript 程序虽然可在 Node.js 环境中正常运行,却没有办法在网页浏览器上正常运行。
把 import 关键字写进 showMessageAndInputText 函数中是铁定行不通的,因为 import 关键字必须要写在程序最外层。
那该怎么做才好?鱼和熊掌不能兼得吗?
由于我们的目的只是要让 TypeScript 能够去抓取传入 require 函数的模块名称(或路径)的 .d.ts 定义档,所以大可不去使用 import 关键字声明出来的名称,就让它因为没有被使用而直接被 TypeScript 在编译阶段省略掉。把它声明出来的用途,只是为了要利用刚才介绍的 typeof 关键字来做类型的拷贝,让猜数字程序内的 readline 变量能够有更精确的类型定义。
修改之后如下:
import _readline = require("node:readline");
const isBrowser: boolean = typeof window === "object";
function showMessage(text: string): void {
if (isBrowser) {
alert(text);
} else {
console.log(text);
}
}
async function showMessageAndInputText(text: string): Promise<string | null> {
if (isBrowser) {
return prompt(text);
} else {
console.log(text);
const readline: typeof _readline = require("node:readline");
const rl = readline.createInterface({ input: process.stdin });
const lineResolver: Promise<string> = new Promise<string>(resolve => {
rl.on("line", (line) => resolve(line));
});
const line: string = await lineResolver;
rl.close();
return line;
}
}
async function main(): Promise<void> {
showMessage("Guess the number!");
const secretNumber: number = Math.floor(Math.random() * 100 + 1);
showMessage(`The secret number is: ${secretNumber}`);
while (true) {
const line: string | null = await showMessageAndInputText("Please input your guess.");
if (line === null) {
continue;
}
const guess: number = parseInt(line);
if (isNaN(guess)) {
showMessage("Please type a number!");
} else {
showMessage(`You guessed: ${guess}`);
if (guess < secretNumber) {
showMessage("Too small!");
} else if (guess > secretNumber) {
showMessage("Too big!");
} else {
showMessage("You win!");
break;
}
}
}
}
main();
如此一来,以上的 TypeScript 程序所编译出来的 JavaScript 程序就可以同时被用在 Node.js 和网页浏览器中。
import 关键字还有很多功能,会在之后的章节详细介绍。另外,注意这边的 import 关键字用法会导致 TypeScript 程序无法在编译目标设为 ES6 或以上时成功编译,我们在之后的章节介绍到模块时会顺便解决这个问题。
函数的转型
前面的章节介绍的对象转型,在严格模式下无法套用在函数的参数类型上。
例如以下程序:
const o: { f1: number, f2: string } = {
f1: 1,
f2: "2",
};
const oo: { f1: number } = o;
const f: (o: { f1: number, f2: string }) => void = (o: { f1: number, f2: string }) => {
};
const ff: (o: { f1: number }) => void = f;
const fff: (o: { f1: number }) => void = (o: { f1: number, f2: string }) => {
};
在严格模式下,变量 ff 和变量 fff 的声明叙述都会编译错误。要在非严格模式下才会编译成功。
但在严格模式下,函数回传的对象类型是可以转型的。
const o: { f1: number, f2: string } = {
f1: 1,
f2: "2",
};
const oo: { f1: number } = o;
const f: () => { f1: number, f2: string } = () => ({
f1: 1,
f2: "2",
});
const ff: () => { f1: number } = f;
const fff: () => { f1: number } = () => ({
f1: 1,
f2: "2",
});
甚至不知道为什么,任何函数的回传值类型都可以转型为 void。
const f1: () => void = () => undefined;
const f2: () => void = () => 1;
const f3: () => void = () => "2";
const f4: () => void = () => false;
const f5: () => void = () => ({ f1: 1, f2: "2" });
此外,就算在严格模式下,函数的参数还是可以在转型时被增加。
const o: { f1: number, f2: string } = {
f1: 1,
f2: "2",
};
const oo: { f1: number } = o;
const f: (o: { f1: number, f2: string }) => void = (o: { f1: number, f2: string }) => {
};
const ff: (o: { f1: number, f2: string, f3: boolean }) => void = f;
const fff: (o: { f1: number, f2: string, f3: boolean }) => void = (o: { f1: number, f2: string }) => {
};
特殊的对象属性
TypeScript 的对象类型预设了几个拥有特殊功能的「属性」。
可被调用的对象类型
假如 f 是一个函数,则 f() 叙述可以调用它。这我们都知道,但还记得先前的章节有提过「函数也是对象」吗?也就是说,函数和对象一样也可以有一些属性。那么问题就来了,如果函数有属性,那它的类型应该要怎么表示呢?
其实很简单,只要直接将函数的类型,写进对象类型的大括号 {} 内,把 => 改为 :,使参数类型的部份作为一个属性,这个对象就会是一个「可被调用」的对象。换句话说,假如 o 是一个对象,则 o() 叙述可以调用它。
举例来说:
const f: (n: number) => number = function (n: number) {
return n + 1;
};
若要替以上这个 f 函数增加属性,可以将其的类型先改为:
const f: { (n: number): number } = function (n: number) {
return n + 1;
};
之后就可以添加任何我们想要的属性。例如:
const f: { (n: number): number, f1?: number, f2?: string } = function (n: number) {
return n + 1;
};
f.f1 = 1;
f.f2 = "2";
console.log(f.f1);
console.log(f.f2);
console.log(f(100));
以上程序,输出结果如下:
2
101
可被「new」的对象类型
假如 F 是一个函数,则 new F() 叙述可以创建出这个函数的对象实体。然而,还记得在前面的章节有提到,在 TypeScript 的严格模式下对于函数我们必须要用 as 关键字将其先强制转型为 any,才能够使用 new 关键字吗?所以 new F() 叙述在严格模式下应该要改为 new (F as any)() 叙述才能编译。
例如:
function F(this: { t: number }, n: number) {
this.t = n;
}
const a = new (F as any)();
console.log(a.t);
虽然以上程序在严格模式下可以编译,但很明显地,这个函数在使用构造器时应该要将一个数值代入 n 参数,而这边的程序第 5 行显然并没有这样做。
我们其实可以自行明确地定义函数的构造器类型,以及建构出来的对象的类型来解决这个问题。构造器的类型定义方式有点像是上面介绍的「可被调用的对象类型」的定义方式,只要直接将构造器的类型,写进对象类型的大括号 {} 内,把 => 改为 :,再在参数类型的部份前加上 new,这个函数(对象)就会是一个「可被 new」的函数(对象)。不过,这个方式依然需要先靠 as any 来转型。
例如:
const F: { new(n: number): { t: number } } = function (this: { t: number }, n: number) {
this.t = n;
} as any;
const a = new F(1);
console.log(a.t);
除非是想快速地将 JavaScript 程序转为 TypeScript 程序,不然一般我们还是会选择使用类别来创建对象,而不是函数。
有多载的对象方法
当对象有了多载方法时,它的类型要怎么表示呢?
先看看以下的这个对象:
const o: { name: string, age: number, studentNumber: string, toString: () => string } = {
name: "David",
age: 18,
studentNumber: "B12345678",
toString: function () {
return `${this.age}: ${this.name}`;
},
};
以上的 o 变量的类型,其实可以改成以下这样:
const o: { name: string, age: number, studentNumber: string, toString(): string } = {
name: "David",
age: 18,
studentNumber: "B12345678",
toString: function () {
return `${this.age}: ${this.name}`;
},
};
我们将 toString 属性的写法直接变成函数类型,但把 => 改为 : 了!透过这样的语法,我们可以在类型中添加更多的 toString 方法,并将程序修改如下:
const o: { name: string, age: number, studentNumber: string, toString(): string, toString(includeStudentNumber: boolean): string } = {
name: "David",
age: 18,
studentNumber: "B12345678",
toString: function (includeStudentNumber?: boolean) {
if (includeStudentNumber) {
return `${this.name}: ${this.age}, ${this.studentNumber}`;
}
return `${this.name}: ${this.age}`;
},
};
如此一来,o 这个对象的 toString 就变成多载方法啦!(虽然实际上它仍然只有一个函数……)
总结
在这个章节中,我们学会了 TypeScript 类型的运算,也利用了 type 关键字来创造类型的别名。我们也学会用 typeof 和 keyof 关键字来拷贝值或键值的类型,还学会函数的转型了。除此之外,我们也了解了对象类型所使用的特殊属性。
在下一个章节中要来补充几个在 ES6 之后才加入的语法,提升我们撰写代码的速度。
