Cast int to enum strings in Typescript

前端 未结 3 1484
-上瘾入骨i
-上瘾入骨i 2020-12-14 05:39

I get from a RESTful Service the following data:

[
  {
    \"id\": 42,
    \"type\": 0,
    \"name\": \"Piety was here\",
    \"description\": \"Bacon is tas         


        
相关标签:
3条回答
  • 2020-12-14 06:20

    I think with

    {{message.type}}
    

    you just get the mapped value and not the enum. Please try following code.

    {{TYPE[message.type]}}
    
    0 讨论(0)
  • 2020-12-14 06:24

    Enums in TypeScript are objects at runtime that have properties that go from int -> string and from string -> int for all possible values.

    To access the string value you will need to call:

    Type[0] // "Info"
    

    Make sure that you are passing the correct type into the property accessor though because chained calls can result in the following:

    Type[Type.Info] // "Info"
    Type[Type[Type.Info]] // 0
    Type["Info"] // 0
    Type[0] // "Info"
    
    0 讨论(0)
  • 2020-12-14 06:27

    Enums in TypeScript are numbers at runtime, so message.type will be 0, 1, 2 or 3.

    To get the string value, you need to pass that number into the enum as an index:

    Type[0] // "Info"
    

    So, in your example, you'll need to do this:

    Type[message.type] // "Info" when message.type is 0
    

    Docs

    0 讨论(0)
提交回复
热议问题