简体   繁体   English

在打字稿中获取枚举的类名

[英]Getting the class name of an Enum in Typescript

I have some enums in my Typescript application and I use code similar to this to get the string value to display in the application:我的 Typescript 应用程序中有一些枚举,我使用与此类似的代码来获取要在应用程序中显示的字符串值:

enum Color{ RED, BLUE, GREEN};

document.write( "The string for Red is: " + Color[Color.RED] );

However, the string value is usually more along the lines of a database key or some other server related string rather than a nicely formatted string fit for display to the user.但是,字符串值通常更接近于数据库键或其他一些与服务器相关的字符串,而不是适合向用户显示的格式良好的字符串。 To get round this I want to load localised property files that use the string value of an enum to look up a nicely formatted string to display in the application.为了解决这个问题,我想加载本地化的属性文件,这些文件使用枚举的字符串值来查找要在应用程序中显示的格式良好的字符串。 The file might look like this:该文件可能如下所示:

Color.properties:
RED=The color is red
BLUE=The color is blue
GREEN=The color is green

I am confident that I can load this file and parse the contents to populate some lookup for later display in the application but I am not sure about how to know which property file to load.我相信我可以加载此文件并解析内容以填充一些查找以供稍后在应用程序中显示,但我不确定如何知道要加载哪个属性文件。 For the following enums对于以下枚举

Color
Shape
Animal

I will have the following property files:我将拥有以下属性文件:

Color.properties
Shape.properties
Animal.properties

My question is: Is there any way of getting the string "Color" from the run time javascript definition of Color?我的问题是:有没有办法从颜色的运行时 javascript 定义中获取字符串“颜色”? The Typescript code for Color gets transpiled into: Color 的 Typescript 代码被转译为:

var Color;
(function (Color) {
    Color[Color["RED"] = 0] = "RED";
    Color[Color["BLUE"] = 1] = "BLUE";
    Color[Color["GREEN"] = 2] = "GREEN";
})(Color || (Color = {}));

I don't think that I can get the String Color out of that in any easy way.我认为我无法以任何简单的方式从中获取字符串颜色。 I assume that I am just going to have to use switch expression to lookup the name of the file.我假设我只需要使用 switch 表达式来查找文件名。

Nope, there's nothing built into the language that allows you to get the name of an enum at runtime.不,该语言没有内置任何内容可以让您在运行时获取枚举的名称。

However, I used the following method to do it:但是,我使用以下方法来做到这一点:

namespace MyEnums {

    export enum Color { RED, BLUE, GREEN };

    export enum Shape { ROUND, SQUARE };

    export function getName(enumObj: any): string {

        for (let name in MyEnums) {
            if ( MyEnums[name] === enumObj && MyEnums.hasOwnProperty(name) ) {
                return name;
            }
        }

        return undefined;
    }
}

const Color = MyEnums.Color;

var name = MyEnums.getName(Color);

Although, I ended up refactoring my code so I wouldn't need to get the names in the end.虽然,我最终重构了我的代码,所以我最终不需要得到名字。

It might be easier to make the file you store your strings in a TypeScript file and then use the actual enum— Color —to do the mapping.将您存储字符串的文件制作在 TypeScript 文件中,然后使用实际的枚举( Color进行映射可能会更容易。

With that said...照这样说...

Is there any way of getting the string "Color" from the run time javascript definition of Color?有没有办法从颜色的运行时javascript定义中获取字符串“颜色”?

A reliable solution is to use something like ts-nameof .一个可靠的解决方案是使用类似ts-nameof 的东西。

Alternatively, you can use a similar trick that's outlined in this answer :或者,您可以使用此答案中概述的类似技巧:

function getVariableName(variableFunction: () => any) {
    return /\s([^\s;]+);?\s*\}$/.exec(variableFunction.toString())[1];
}

var variableName = getVariableName(() => Color); // returns string "Color"

This wraps Color in a function then calls .toString() on that function.这将 Color 包装在一个函数中,然后对该函数调用.toString() Using that string it will extract out only the name provided.使用该字符串,它将仅提取提供的名称。

Just make sure you test to see if this works after being minified.只要确保在缩小后进行测试,看看这是否有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM