TS2476

error TS2476: A const enum member can only be accessed using a string literal.

Broken Code ❌

1
2
3
4
5
6
const enum OrderSide {
BUY = 'buy',
SELL = 'sell',
}

console.log(OrderSide[0]);

Fixed Code ✔️

Constant enumerations can only be accessed using key names:

1
2
3
4
5
6
const enum OrderSide {
BUY = 'buy',
SELL = 'sell',
}

console.log(OrderSide.BUY);

If you want to access enums by indices, you must remove the const keyword and values from your enum:

1
2
3
4
5
6
enum OrderSide {
BUY,
SELL,
}

console.log(OrderSide[0]);

⚠️ Be aware that this may become unsafe as you may unintentionally access indices that are not defined.