gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:19:57 28 4
gpt4 key购买 nike

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

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

我正在映射这个类:

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


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

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

例如:

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

最佳答案

TypeScript 中的枚举是运行时的数字,因此 message.type 将为 0123

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

Type[0] // "Info"

因此,在您的示例中,您需要这样做:

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

Docs

关于javascript - 将 int 转换为 Typescript 中的枚举字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42299257/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com