字符串枚举的反向映射 [英] Reverse-Mapping for String Enums

查看:192
本文介绍了字符串枚举的反向映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wanted to use string enums in typescript but I can't see a support for reversed mapping in it. I have an enum like this:

enum Mode {
    Silent = "Silent",
    Normal = "Normal",
    Deleted = "Deleted"
}

我需要这样使用它:

let modeStr: string;
let mode: Mode = Mode[modeStr];

是的,我不知道它在modeStr字符串中是什么,并且我需要将其解析为枚举,或者如果在枚举定义中未显示该字符串,则会在运行时解析失败. 我该如何做到整洁呢? 预先感谢

and yes I don't know what is it there in modeStr string and I need it parsed to the enum or a fail at parsing in runtime if the string is not presented in the enum definition. How can I do that as neat as it can be? thanks in advance

推荐答案

我们可以将Mode设置为类型,并将值设置为相同的类型.

We can make the Mode to be a type and a value at the same type.

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

这篇关于字符串枚举的反向映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆