简体   繁体   中英

How can I use enum values as index of array

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?

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, ie you cannot assign a new value to the binding.

Object.freeze works on values, and more specifically, object values. It makes an object immutable, ie 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

Try this.

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

    module.exports = color

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM