Javascript 将 int 转换为 Typescript 中的枚举字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42299257/
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-08-23 01:02:32  来源:igfitidea点击:

Cast int to enum strings in Typescript

javascriptangulartypescriptenums

提问by Franz Peter Tebartz van Elst

I get from a RESTful Service the following data:

我从 RESTful 服务获得以下数据:

[
  {
    "id": 42,
    "type": 0,
    "name": "Piety was here",
    "description": "Bacon is tasty, tofu not, ain't nobody like me, cause i'm hot...",
  }...

And I'm mapping with this class:

我正在用这个类映射:

export enum Type {
  Info,
  Warning,
  Error,
  Fatal,
}


export class Message{
  public id: number;
  public type: Type:
  public name: string;
  public description: string;
}

But when I access 'type' in Angular2 I get only a int value. But I'd like to get a string value.

但是当我在 Angular2 中访问“type”时,我只得到一个 int 值。但我想得到一个字符串值。

e.g:

例如:

'message.type=0'
{{message.type}} => should be Info
'message.type=1'
{{message.type}} => should be Warning

回答by James Monger

Enums in TypeScript are numbers at runtime, so message.typewill be 0, 1, 2or 3.

在打字稿枚举是在运行时的数字,所以message.type0123

To get the string value, you need to pass that number into the enum as an index:

要获取字符串值,您需要将该数字作为索引传递到枚举中:

Type[0] // "Info"

So, in your example, you'll need to do this:

因此,在您的示例中,您需要执行以下操作:

Type[message.type] // "Info" when message.type is 0

Docs

文档

回答by Teddy Sterne

Enums in TypeScript are objects at runtime that have properties that go from int -> stringand from string -> intfor all possible values.

在打字稿枚举是在运行时有从去属性的对象int -> string,并从string -> int所有可能的值。

To access the string value you will need to call:

要访问字符串值,您需要调用:

Type[0] // "Info"

Make sure that you are passing the correct type into the property accessor though because chained calls can result in the following:

确保您将正确的类型传递给属性访问器,因为链接调用可能会导致以下结果:

Type[Type.Info] // "Info"
Type[Type[Type.Info]] // 0
Type["Info"] // 0
Type[0] // "Info"

回答by C.Stebner

I think with

我认为与

{{message.type}}

you just get the mapped value and not the enum. Please try following code.

你只得到映射值而不是枚举。请尝试以下代码。

{{TYPE[message.type]}}