What is the “type” reserved word in TypeScript?

前端 未结 2 1641
执念已碎
执念已碎 2020-12-02 13:01

I just noticed when trying to create an interface in TypeScript that \"type\" is either a keyword or a reserved word. When creating the following interface, for example, \"t

2条回答
  •  天命终不由人
    2020-12-02 13:28

    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 has the types random and color in it.

    Then when we try to make a string literal our (and we have IntelliSense 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.

提交回复
热议问题