5

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?

locke14
  • 1,335
  • 3
  • 15
  • 36
sally
  • 379
  • 2
  • 8
  • 17
  • 3
    Thats not an enum. And `Color.RED` is not an instance of `Color`. – tkausl Jul 08 '19 at 07:35
  • 2
    Works for me in plain JS in Chrome if I remove the export keyword – mplungjan Jul 08 '19 at 07:40
  • 3
    @mplungjan same here. But not in firefox - it reports that fields are not yet supported. – VLAZ Jul 08 '19 at 07:40
  • 2
    It only shows this error when you have `x[Color]` instead of `x[Color.RED]` [Typescript Playground](https://www.typescriptlang.org/play/index.html#code/MYGwhgzhAEDCD2J4CdoG8BQ1vQgFzDwEthoAlAUQBFoBeaABgG4sd9CToAhAGQFUKdaAEYWOXAWKkA4pQoA5IQCYWAXwwYQAUzzQAHkIDaAcgDuYZADsilgObGANNGM2AZvEfOIAV2DAtUMYAuizaumCW8HgAFlrIAGoWRGAARtpCeoYISMghQA) – adiga Jul 08 '19 at 07:51

2 Answers2

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

claasic
  • 1,050
  • 6
  • 14
0

Try this.

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

    module.exports = color

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