How to create enum like type in TypeScript?

后端 未结 6 1101
南旧
南旧 2020-12-08 09:07

I\'m working on a definitions file for the Google maps API for TypeScript.

And I need to define an enum like type eg. google.maps.Animation which contai

6条回答
  •  爱一瞬间的悲伤
    2020-12-08 09:37

    Enums in typescript:

    Enums are put into the typescript language to define a set of named constants. Using enums can make our life easier. The reason for this is that these constants are often easier to read than the value which the enum represents.

    Creating a enum:

    enum Direction {
        Up = 1,
        Down,
        Left,
        Right,
    }
    

    This example from the typescript docs explains very nicely how enums work. Notice that our first enum value (Up) is initialized with 1. All the following members of the number enum are then auto incremented from this value (i.e. Down = 2, Left = 3, Right = 4). If we didn't initialize the first value with 1 the enum would start at 0 and then auto increment (i.e. Down = 1, Left = 2, Right = 3).

    Using an enum:

    We can access the values of the enum in the following manner:

    Direction.Up;     // first the enum name, then the dot operator followed by the enum value
    Direction.Down;
    

    Notice that this way we are much more descriptive in the way we write our code. Enums basically prevent us from using magic numbers (numbers which represent some entity because the programmer has given a meaning to them in a certain context). Magic numbers are bad because of the following reasons:

    1. We need to think harder, we first need to translate the number to an entity before we can reason about our code.
    2. If we review our code after a long while, or other programmers review our code, they don't necessarily know what is meant with these numbers.

提交回复
热议问题