在打字稿中是否可以在枚举中使用字符串变量?我可以像这样在枚举中使用字符串:
enum AllDirections {
TOP = 'top',
BOTTOM = 'bottom',
LEFT = 'left',
RIGHT = 'right',
}
Run Code Online (Sandbox Code Playgroud)
但是这段代码:
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,
}
Run Code Online (Sandbox Code Playgroud)
结果有错误:Type 'string' is not assignable to type 'AllDirections'
如果您确实想这样做,那么您可以将这些值断言为any:
enum AllDirections {
TOP = top as any,
BOTTOM = bottom as any,
LEFT = left as any,
RIGHT = right as any
}
Run Code Online (Sandbox Code Playgroud)
这样做的问题是,如果您将它们分配给字符串值,那么它将需要对字符串进行断言。这并不理想:
let str: string = AllDirections.TOP as any as string;
Run Code Online (Sandbox Code Playgroud)
或者,它有点冗长,但如果您希望成员具有正确的类型,您可以考虑使用对象:
// 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
};
Run Code Online (Sandbox Code Playgroud)
另一种选择是翻转字符串的存储位置:
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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1763 次 |
| 最近记录: |