How can I use enum values as index of array

177
July 08, 2019, at 1:40 PM

I try to use enum value as index of array but it gives me an error.

export class Color {
    static RED = 0;
    static BLUE = 1;
    static GREEN = 2;
}
let x = ['warning', 'info', 'success'];
let anotherVariable = x[Color.RED]; <---- Error: Type 'Color' cannot be used as an index type.

I tried Number() and parseInt to convert to number but it does not work.

Is there any way that I can use Enum values as an index?

Answer 1

To create an Enum we create a const frozen object. For the difference and why see the below quote:

const applies to bindings ("variables"). It creates an immutable binding, i.e. you cannot assign a new value to the binding.

Object.freeze works on values, and more specifically, object values. It makes an object immutable, i.e. you cannot change its properties.

From: https://stackoverflow.com/a/33128023/9758920

Afterwards we can still access the keys and values like with a normal object.

// https://stackoverflow.com/questions/287903/what-is-the-preferred-syntax-for-defining-enums-in-javascript 
const COLORS = Object.freeze({"RED":0, "BLUE":1, "GREEN":2}) 
 
let x = ['warning', 'info', 'success']; 
let anotherVariable = x[COLORS.RED];  
 
console.log(anotherVariable)

Also check out: https://stackoverflow.com/a/49309248/9758920

Answer 2

Try this.

    let color = {
        RED : 0,
        BLUE : 1,
        GREEN : 2
    }
    module.exports = color
    let x = ['warning', 'info', 'success'];
    let anotherVariable = x[color.RED];
Rent Charter Buses Company
READ ALSO
How can we open my website only chrome browser? Should not open in firefox, uc browser etc

How can we open my website only chrome browser? Should not open in firefox, uc browser etc

I want that my website only open in chrome browserIt should not open in any other browser like uc browser ,firefox etc

123
how to get sum inside scope?

how to get sum inside scope?

how to sum value inside Scope and store to another scope variable ?

172
Force video to play before poster loads

Force video to play before poster loads

On firefox the poster image completely loads before video startsIs it possible to force it to play video first with either pure JS or jquery? Doesn't matter if it stops to buffer, i just don't want to see the poster first

135