Insert int to enumerate strings in Typescript

I get the following data from a RESTful service:

[ { "id": 42, "type": 0, "name": "Piety was here", "description": "Bacon is tasty, tofu not, ain't nobody like me, cause i'm hot...", }... 

And I map to this class:

 export enum Type { Info, Warning, Error, Fatal, } export class Message{ public id: number; public type: Type: public name: string; public description: string; } 

But when I access the 'type' in Angular2, I only get the int value. But I would like to get a string value.

eg:

 'message.type=0' {{message.type}} => should be Info 'message.type=1' {{message.type}} => should be Warning 
+8
javascript enums angular typescript
source share
3 answers

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

To get a string value, you need to pass this number to the enumeration as an index:

 Type[0] // "Info" 

So in your example you will need to do this:

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

Docs

+10
source share

Enumerations in TypeScript are runtime objects that have properties that come from int -> string and from string -> int for all possible values.

To access a string value, you need to call:

 Type[0] // "Info" 

Make sure that you pass the correct type to the accessory properties, although due to the fact that related calls can lead to the following:

 Type[Type.Info] // "Info" Type[Type[Type.Info]] // 0 Type["Info"] // 0 Type[0] // "Info" 
+8
source share

I think,

 {{message.type}} 

you will only get the displayed value, not an enumeration. Please try the following code.

 {{TYPE[message.type]}} 
0
source share

All Articles