6

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?

4
  • 3
    Thats not an enum. And Color.RED is not an instance of Color. Commented Jul 8, 2019 at 7:35
  • 2
    Works for me in plain JS in Chrome if I remove the export keyword Commented Jul 8, 2019 at 7:40
  • 3
    @mplungjan same here. But not in firefox - it reports that fields are not yet supported. Commented Jul 8, 2019 at 7:40
  • 2
    It only shows this error when you have x[Color] instead of x[Color.RED] Typescript Playground Commented Jul 8, 2019 at 7:51

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't answer why the posted code is throwing the error
As seen from the comments: very likely a browser support problem.
0

Try this.

    let color = {
        RED : 0,
        BLUE : 1,
        GREEN : 2
    }

    module.exports = color

    let x = ['warning', 'info', 'success'];
    let anotherVariable = x[color.RED];

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.