TypeScript 中的 "type" 保留字是什么?

What is the "type" reserved word in TypeScript?

我刚刚在尝试在 TypeScript 中创建接口时注意到 "type" 是关键字或保留字。创建如下界面时,例如 "type" 在 Visual Studio 2013 with TypeScript 1.4 中显示为蓝色:

interface IExampleInterface {
    type: string;
}

假设您随后尝试在 class 中实现接口,如下所示:

class ExampleClass implements IExampleInterface {
    public type: string;

    constructor() {
        this.type = "Example";
    }
}

在 class 的第一行,当您键入(抱歉)单词 "type" 以实现接口所需的 属性 时,IntelliSense 会出现 "type" 与 "typeof" 或 "new".

等其他关键字具有相同的图标

我环顾四周,可以找到这个 GitHub issue,它在 TypeScript 中将 "type" 列为 "strict mode reserved word",但我还没有找到关于它的内容的任何进一步信息目的其实是。

我怀疑我脑子放屁了,这是我应该已经知道的显而易见的事情,但是 TypeScript 中的 "type" 保留字是干什么用的?

它用于“类型别名”。例如:

type StringOrNumber = string | number;
type DictionaryOfStringAndPerson = Dictionary<string, Person>;

参考:(编辑:删除了过时的 link) TypeScript 规范 v1.5(第 3.9 节,“类型别名”,第 46 和 47 页)

更新(编辑:删除了过时的 link) 现在是 1.8 规范的第 3.10 节。感谢@RandallFlagg 更新规范和 link

Update: (edit: deprecated link) TypeScript Handbook, 搜索“Type Aliases”可以得到你到相应的部分。

更新:现在是here in the TypeScript Handbook

在打字稿中输入关键字:

在打字稿中,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;

您可以组合标量类型(stringnumber 等),也可以组合文字值,如 1'mystring'。您甚至可以组合其他用户定义类型的类型。例如类型 madness 中有类型 randomcolor

然后当我们尝试使字符串文字成为我们的(我们的 IDE 中有 IntelliSense)时,它会显示建议:

它显示了所有的颜色,madness 类型派生自 color 类型,'random' 派生自 random 类型,最后是 madness 类型本身的字符串 'foo'