TypeScript中的“type”保留字是什么意思?

146

我刚刚在尝试使用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”或“new”)具有相同的图标。

我查看了一些资料,并找到了这个GitHub问题,其中将“type”列为TypeScript中的“严格模式保留字”,但我没有找到任何进一步的信息来了解它的实际用途。

我认为我正在脑残,这是我应该已经知道的明显的东西,但是TypeScript中的“type”保留字是什么意思?


1
类型别名(Type Alias):为您的类型赋予语义名称:http://basarat.gitbooks.io/typescript/content/docs/types/type-system.html - basarat
3个回答

183

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

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

参考资料:(编辑:已删除过时链接) TypeScript规范V1.5(第3.9节“类型别名”,第46页和47页)

更新(编辑:已删除过时链接) 现在在1.8规范的第3.10节。感谢@RandallFlagg提供更新后的规范和链接。

更新(编辑:已弃用链接) TypeScript手册,搜索“类型别名”即可找到相应部分。

更新:现在在TypeScript手册中


41
没错,这是显而易见的事情。原来在编程语言上下文中搜索单词"type"时很难找到你要找的东西 - 特别是当所涉及的语言叫做"TypeScript"时。顺便问一下,在TypeScript中还没有泛型字典吧? - Adam Goodwin
1
如果您需要的话,这里有一个(https://github.com/basarat/typescript-collections)(适用于TS 0.9及以上版本): - Jcl
谢谢,我想我曾经在需要词典时看过那个项目,但最终我决定不用它。 - Adam Goodwin
这个概念来自于C语言中的typedef,可以查看此链接:https://www.studytonight.com/c/typedef.php。 - Pranoy Sarkar
前两个链接已经失效,请更新,谢谢 :) - Serkan Sipahi
@SerkanSipahi移除了过时的链接,但为了清晰起见保留了文本。谢谢 :-) - Jcl

50

在 TypeScript 中使用 type 关键字:

在 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

它显示了所有颜色,这些颜色来自于类型 madness 派生出的 color 类型,派生出的随机类型 'random',以及最后在类型 madness 自身上的字符串 'foo'


2
用户定义类型和可枚举类型有什么区别? - ORcoder
1
@ORcoder 好问题!我也想知道。一个好的解释让我们理解! - Merv
你已经在类内部还是外部声明了 type color = "blue" | "red" | "yellow" | "purple"; 语句? - Lalit Kushwah
关于用户定义类型和枚举之间的区别,这篇文章可能会有所帮助。 - Christophe Fuzier
类型关键字及其值应在类外声明。 - Prabhakaran M

0
类型别名允许使用自定义名称(别名)定义类型。
类型别名可用于原始类型,如字符串或更复杂的类型,例如对象和数组:
示例:
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
};

参考资料


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接