TransWikia.com

Get index of enum value typescript

Stack Overflow Asked by Héloïse Chauvel on December 4, 2021

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 Answers

It's simple to get enum value by name:

const enumValue = SampleEnum["enumName"];

Answered by Masih Jahangiri on December 4, 2021

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');

Answered by saulmaldonado on December 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP