16

I have the following string enum:

export enum RecordStatus {
   ONGOING_ADMINISTRATIVE_ANALYSIS = 'ONGOING_ADMINISTRATIVE_ANALYSIS',

   ONGOING_TECHNICAL_ANALYSIS = 'ONGOING_TECHNICAL_ANALYSIS',

   COMPLETED_APPLICATION = 'COMPLETED_APPLICATION'
}

I have the following function:

setTimelineStatus(status: RecordStatus) : void {
    console.log("State :" + status); // ON_GOING_TECHNICAL_ANALYSIS

    console.log(RecordStatus.valueOf(status).ordinal()); // doesn't work. Should print 1

    console.log(RecordStatus.valueOf("ON_GOING_TECHNICAL_ANALYSIS").ordinal()); // doesn't work either. Should print 1
}

This function retrieves a set enum as parameter, for example RecordStatus.ON_GOING_TECHNICAL_ANALYSIS. I want to get the index (it should be 1 in above case). I tried the solution in this thread Get index of enum from string? but I've got this error:

Error

I don't understand why I have this error. I only want the index of the enum value.

2

2 Answers 2

18

The post you are refering to is for enums in Java.

In TypeScript, enum are considered objects at runtime so you can just iterate over the keys of the enum until you find the one you're looking for.

Object.keys(RecordStatus).indexOf('ON_GOING_TECHNICAL_ANALYSIS');
Sign up to request clarification or add additional context in comments.

2 Comments

I didn't see it was Java! It works with console.log(Object.keys(RecordStatus).indexOf(status)); (the parameter), however when I try with your suggestion I get -1. But it doesn't matter, I have the solution, thanks!
@HéloïseChauvel the reason you are getting -1 is because it is incorrectly spelled. It should be ONGOING_TECHNICAL_ANALYSIS (note the _ that is removed after ON), based on your enum stated above.
2

This code returns the index of enum item. Besides it TypeScript-guarded, i.e. would not allow to make a mistake in the enum item identifier, provided your IDE supports TypeScript:

Object.values(RecordStatus).indexOf(RecordStatus.ONGOING_ADMINISTRATIVE_ANALYSIS)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.