What is the “type” reserved word in TypeScript?

落爺英雄遲暮 提交于 2019-11-28 06:07:44

It's used for "type aliases". For example:

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

Reference: TypeScript Specification v1.5 (section 3.9, "Type Aliases", pages 46 & 47)

Update: Now on section 3.10 of the 1.8 spec. Thanks @RandallFlagg for the updated spec and link

Update: TypeScript Handbook, search "Type Aliases" can get you to the corresponding section.

Type keyword in typescript:

In typescript the type keyword defines an alias to a type. We can also use the type keyword to define user defined types. This is best explained via an example:

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;

You can compose types of scalar types (string, number, etc), but also of literal values like 1 or 'mystring'. You can even compose types of other user defined types. For example type madness which has the types random and color in it.

Then when we try to make a string literal our (and we have intelliscence in our IDE) it shows suggestions:

It shows all the colors, which type madness derives from having type color, 'random' which is derived from type random, and finally the string 'foo' which is on the type madness itself.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!