我刚刚注意到,当尝试在 TypeScript 中创建接口时,“type”要么是关键字,要么是保留字。例如,创建以下界面时,“type”在带有 TypeScript 1.4 的 Visual Studio 2013 中显示为蓝色:
interface IExampleInterface {
type: string;
}
假设您随后尝试在类中实现该接口,如下所示:
class ExampleClass implements IExampleInterface {
public type: string;
constructor() {
this.type = "Example";
}
}
在类的第一行中,当您键入(抱歉)单词“type”以实现接口所需的属性时,IntelliSense 会显示“type”,其图标与其他关键字(如“typeof”或“新”。
我环顾四周,可以找到这个 GitHub 问题,其中将“type”列为 TypeScript 中的“严格模式保留字”,但我还没有找到有关其实际用途的任何进一步信息。
我怀疑我脑子里放屁了,这是我应该已经知道的明显事情,但是 TypeScript 中的“type”保留字是做什么用的?
它用于“类型别名”。例如:
type StringOrNumber = string | number;
type DictionaryOfStringAndPerson = Dictionary<string, Person>;
作为参考,TypeScript 手册中有一个类型别名部分。
在打字稿中,type 关键字定义类型的别名。我们还可以使用 type 关键字来定义用户定义的类型。通过一个例子可以最好地解释这一点:
type Age = number | string; // pipe means number OR string
type color = "blue" | "red" | "yellow" | "purple";
type random = 1 | 2 | 'random' | boolean;
// random and color refer to user defined types, so type madness can contain anything which
// within these types + the number value 3 and string value 'foo'
type madness = random | 3 | 'foo' | color;
type error = Error | null;
type callBack = (err: error, res: color) => random;
您可以组合标量类型(
string
、number
等),也可以组合文字值,如1
或'mystring'
。您甚至可以组合其他用户定义类型的类型。例如,类型 madness
包含类型 random
和 color
。
然后,当我们尝试将字符串文字设为我们的(并且我们的 IDE 中有 IntelliSense)时,它会显示建议:
它显示了所有颜色,其中类型 madness 源自颜色类型,“随机”源自类型 random,最后是字符串
'foo'
,它位于类型 madness 本身。
类型别名允许使用自定义名称(别名)定义类型。
类型别名可用于字符串或更复杂的基元 对象和数组等类型:
示例:
type CarYear = number
type CarType = string
type CarModel = string
type Car = {
year: CarYear,
type: CarType,
model: CarModel
}
const carYear: CarYear = 2001
const carType: CarType = "Toyota"
const carModel: CarModel = "Corolla"
const car: Car = {
year: carYear,
type: carType,
model: carModel
};