Reputation: 14886
What is the proper way to map enum in typescript?
For instance I am playing around with an online typescript code editor and this works fine:
class Message
{
name: string;
min: number;
max: number;
messageType: MessageType;
}
enum MessageType
{
none,
email,
sms
}
var jsonObj = {
"name": "some name",
"min": 0,
"max": 10,
"messageType": MessageType.email
}
var messageInstance: Message = <Message>jsonObj;
console.log(messageInstance);
However, in my IDE MessageType.email
shows an error of "value expected" if I use it in a json file.
If I try:
"messageType": "MessageType.email"
In the online code editor then that generates an error.
I am just getting started and can't find any clear instructions on how this should be done.
edit:
I just realised enums are number based so "messageType": 2
or whatever corresponding number would be the correct way to go.
Is there any way to make the enum readable in the json file (i.e. something like MessageType.email as a value) as when viewed alone the json file doesn't have the enum definitions so might be confusing so I'd rather do it that way if possible..
Upvotes: 3
Views: 7141
Reputation: 4016
For TypeScript 2.4+:
You can use string enums instead of a numeric enum:
enum MessageType
{
none = "none",
email = "email",
sms = "sms"
}
For older versions of TypeScript:
You can convert an enum
value to a string
using the enum
's indexer:
const messageTypeAsString = MessageType[MessageType.email];
Going the other way works too:
const messageType: MessageType = MessageType[messageTypeAsString];
As far as I know there is no way to automate this conversion when serializing/deserializing JSON.
The other option is to skip enum
entirely and use static string
s instead:
class MessageType {
static readonly none = 'none';
static readonly email = 'email';
static readonly sms = 'sms';
}
type MessageTypeValue = 'none' | 'email' | 'sms';
const messageType: MessageTypeValue = MessageType.none;
Upvotes: 6