typescript 字符串枚举的反向映射

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44883072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:40:49  来源:igfitidea点击:

Reverse-Mapping for String Enums

javascriptnode.jstypescriptvisual-studio-codemsdn

提问by Kamyar Ghajar

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"
}

and I need to use it like this:

我需要像这样使用它:

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

and yes I don't know what is it there in modeStrstring 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

是的,我不知道modeStr字符串中有什么,如果字符串未出现在枚举定义中,我需要将其解析为枚举或在运行时解析失败。我怎样才能做到尽可能整洁?提前致谢

采纳答案by Rodris

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

我们可以使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"

A more strict version:

更严格的版本:

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

String Enum as this answer:

字符串枚举作为这个答案

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

回答by forivall

If you're ok with using Proxies, I made a more generic & compact version:

如果您可以使用代理,我制作了一个更通用和紧凑的版本:

stringEnum.ts

字符串枚举.ts

export type StringEnum<T extends string> = {[K in T]: K}
const proxy = new Proxy({}, {
  get(target, property) {
    return property;
  }
})
export default function stringEnum<T extends string>(): StringEnum<T> {
  return proxy as StringEnum<T>;
}

Usage:

用法:

import stringEnum from './stringEnum';
type Mode = "Silent" | "Normal" | "Deleted";
const Mode = stringEnum<Mode>();

回答by PhiLho

The cleanest way I found so far is to make a secondary map:

到目前为止,我发现的最干净的方法是制作辅助地图:

let reverseMode = new Map<string, Mode>();
Object.keys(Mode).forEach((mode: Mode) => {
    const modeValue: string = Mode[<any>mode];
    reverseMode.set(modeValue, mode);
});

Thus you can do let mode: Mode = reverseMode.get('Silent');

这样你就可以做到 let mode: Mode = reverseMode.get('Silent');

Advantages: no need to repeat the values, provides a way to enumerate the enum, keeps TSLint happy...

优点:不需要重复值,提供了枚举枚举的方法,让TSLint开心...

Edit: I originally write Mode[mode]but then TS might throw the error TS7015 on this line, so I added the cast.

编辑:我最初写Mode[mode]但后来 TS 可能会在这一行上抛出错误 TS7015,所以我添加了演员表。