1

Is it possible in typescript to use string variables in enum? I can use strings in enum like this:

enum AllDirections {
  TOP = 'top',
  BOTTOM = 'bottom',
  LEFT = 'left',
  RIGHT = 'right',
}

But this code:

const top: string = 'top'
const bottom: string = 'bottom'
const left: string = 'left'
const right: string = 'right'

enum AllDirections {
  TOP = top,
  BOTTOM = bottom,
  LEFT = left,
  RIGHT = right,
}

results with error: Type 'string' is not assignable to type 'AllDirections'

2
  • Why do you want top and AllDirections.TOP? Commented Nov 25, 2017 at 14:10
  • This is just an example for error reproducing. In fact I'm trying to import a list of redux action types from one file that contains all available actions and assign them to enum in another file to be able to use this enum as type in reducer. Commented Nov 25, 2017 at 14:22

1 Answer 1

5

If you really want to do this, then you could assert the values to any:

enum AllDirections {
  TOP = top as any,
  BOTTOM = bottom as any,
  LEFT = left as any,
  RIGHT = right as any
}

The problem with this, is that if you're assigning these to string values, then it will require an assertion to a string. That's not ideal:

let str: string = AllDirections.TOP as any as string;

Alternatively, it's a little verbose, but if you want the members to have the correct type you could consider using an object:

// remove the explicit string types so that these are typed
// as their string literal values
const top = 'top';
const bottom = 'bottom';
const left = 'left';
const right = 'right';

type AllDirections = Readonly<{
    TOP: typeof top,
    BOTTOM: typeof bottom,
    LEFT: typeof left,
    RIGHT: typeof right
}>; 

const AllDirections: AllDirections = {
    TOP: top,
    BOTTOM: bottom,
    LEFT: left,
    RIGHT: right
};

Another option is to flip where the string is stored:

 enum AllDirections {
    TOP = 'top',
    BOTTOM = 'bottom',
    LEFT = 'left',
    RIGHT = 'right',
}

const top = AllDirections.TOP;
const bottom = AllDirections.BOTTOM;
const left = AllDirections.LEFT;
const right = AllDirections.RIGHT;
Sign up to request clarification or add additional context in comments.

1 Comment

The second solution is perfect for me. Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.