How to get string value from a enum in typescript?

Viewed 505

I have an enum of string values. I want to pass a string value to enum and get the value from it.

export enum OperationType  {
    CREATE = "CREATE",
    UPDATE = "UPDATE"
}

I have class as well

class Item {
type:string;
id:string
date:string
}

Now i am calling below function

function sendData(type:OperationType) {
//Do some work
}

Now i want to pass the value in enum like this but i am not able to do

//Here item.type = "CREATE"

sendData(OperationType[item.type])

But this is now allowed i get compile time error of wrong type. Please tell me how can i achieve?

EDIT: Error is

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof OperationType'.

2 Answers

In your case I'd use unions:

type OperationType = "CREATE" | "UPDATE";

class Item {
  type: OperationType;
  id: string;
  date: string;
}

function sendData(type: OperationType) {
  //Do some work
}

This approach provides same IDE intelligence and type checking. Otherwise, you can just change type: OperationType;.

Also you can use const enums. const modifier makes enum readonly and tells compiler not to generate reverse mapping;

export const enum OperationType  {
    CREATE = "CREATE",
    UPDATE = "UPDATE"
}

What's wrong here is the type of the parameter inside the sendData fn definition. That should be a string. You are telling ts that that is an Enum type, not the actual string.

so the fn definition should look like this:

function sendData(type: String) {
//Do some work
}
Related