TypeScript中的"类型"保留字是什么?

Ada*_*win 81 reserved-words keyword typescript

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

interface IExampleInterface {
    type: string;
}
Run Code Online (Sandbox Code Playgroud)

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

class ExampleClass implements IExampleInterface {
    public type: string;

    constructor() {
        this.type = "Example";
    }
}
Run Code Online (Sandbox Code Playgroud)

在类的第一行,当您键入(抱歉)单词"type"以实现接口所需的属性时,IntelliSense会显示"type",其图标与"typeof"或"new"等其他关键字相同".

我已经浏览了一下,并且可以找到这个GitHub问题,它在TypeScript中将"type"列为"严格模式保留字",但我还没有找到任何关于其目的实际是什么的进一步信息.

我怀疑我有一个大脑放屁,这是我应该已经知道的明显的东西,但是TypeScript中的"类型"保留字是什么?

Jcl*_*Jcl 102

它用于"类型别名".例如:

type StringOrNumber = string | number;
type DictionaryOfStringAndPerson = Dictionary<string, Person>;
Run Code Online (Sandbox Code Playgroud)

参考:TypeScript Specification v1.5(第3.9节"类型别名",第46和47页)

更新:现在在1.8规范的3.10节.感谢@RandallFlagg获取更新的规范和链接

更新:TypeScript手册,搜索"类型别名"可以到达相应的部分.

  • 是的,这是显而易见的事情.事实证明,当您在编程语言环境中搜索"类型"一词时,很难找到您正在寻找的内容 - 特别是当所讨论的语言被称为"TypeScript"时.顺便说一下,TypeScript中仍然不存在通用词典吗? (23认同)

Wil*_*een 19

在打字稿中输入关键字:

在打字稿中,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;
Run Code Online (Sandbox Code Playgroud)

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

然后,当我们尝试将字符串文字转换为我们的文字(并且在IDE中具有智能功能)时,它会显示以下建议:

在此处输入图片说明

它显示了所有颜色(疯狂类型是从具有颜色的类型中派生的),“随机”(从随机类型中派生的),最后'foo'是疯狂类型本身上的字符串。

  • 用户定义类型和枚举有什么区别 (2认同)