首页 文章

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

提问于
浏览
62

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

interface IExampleInterface {
    type: string;
}

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

class ExampleClass implements IExampleInterface {
    public type: string;

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

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

我已经浏览了一下,并且可以找到GitHub issue,它将"type"列为TypeScript中的"strict mode reserved word",但我还没有找到任何关于它的目的是什么的进一步信息 .

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

2 回答

  • 76

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

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

    参考:TypeScript Specification v1.5(第3.9节,"Type Aliases",第46和47页)

    UpdateNow on section 3.10 of the 1.8 spec . 感谢@RandallFlagg获取更新的规范和链接

    UpdateTypeScript Handbook,搜索"Type Aliases"可以到达相应的部分 .

  • 5

    打字稿中的类型关键字:

    在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;
    

    您可以组合标量类型( stringnumber 等)的类型,也可以组合文字值,如 1'mystring' . 您甚至可以撰写其他用户定义类型的类型 . 例如,键入 madness ,其中包含 randomcolor 类型 .

    然后,当我们尝试创建一个字符串文字(我们在IDE中有智能)时,它会显示建议:

    enter image description here

    它显示了所有颜色,其类型疯狂来自于具有类型颜色,'random'是从随机类型派生的,最后是字符串 'foo' ,它是疯狂类型本身 .

相关问题