字符串枚举的反向映射

我想在打字稿中使用字符串枚举,但在其中看不到对反向映射的支持。我有一个这样的枚举:

enum Mode {

Silent = "Silent",

Normal = "Normal",

Deleted = "Deleted"

}

我需要这样使用它:

let modeStr: string;

let mode: Mode = Mode[modeStr];

是的,我不知道modeStr字符串中有什么,如果字符串未在枚举定义中显示,我需要将其解析为枚举或在运行时解析失败。我该如何做到整洁呢?提前致谢

回答:

我们可以将其Mode设为一个类型,并将值设为同一类型。

type Mode = string;

let Mode = {

Silent: "Silent",

Normal: "Normal",

Deleted: "Deleted"

}

let modeStr: string = "Silent";

let mode: Mode;

mode = Mode[modeStr]; // Silent

mode = Mode.Normal; // Normal

mode = "Deleted"; // Deleted

mode = Mode["unknown"]; // undefined

mode = "invalid"; // "invalid"

更严格的版本:

type Mode = "Silent" | "Normal" | "Deleted";

const Mode = {

get Silent(): Mode { return "Silent"; },

get Normal(): Mode { return "Normal"; },

get Deleted(): Mode { return "Deleted"; }

}

let modeStr: string = "Silent";

let mode: Mode;

mode = Mode[modeStr]; // Silent

mode = Mode.Normal; // Normal

mode = "Deleted"; // Deleted

mode = Mode["unknown"]; // undefined

//mode = "invalid"; // Error

字符串枚举作为此答案:

enum Mode {

Silent = <any>"Silent",

Normal = <any>"Normal",

Deleted = <any>"Deleted"

}

let modeStr: string = "Silent";

let mode: Mode;

mode = Mode[modeStr]; // Silent

mode = Mode.Normal; // Normal

//mode = "Deleted"; // Error

mode = Mode["unknown"]; // undefined

以上是 字符串枚举的反向映射 的全部内容, 来源链接: utcz.com/qa/413988.html

回到顶部