Use string variables in typescript's enum

时间:2017-11-25 14:06:53

标签: typescript enums

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'

1 个答案:

答案 0 :(得分:3)

如果你真的想这样做,那么你可以将值断言为any

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

问题在于,如果您将这些字符串赋值给字符串值,则需要断言字符串。那不太理想:

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

或者,它有点冗长,但是如果你想让成员拥有正确的类型,你可以考虑使用一个对象:

// 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
};

另一种选择是翻转存储字符串的位置:

 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;