Javascript 在Typescript中将int强制转换为枚举字符串
我从RESTful服务中获得以下数据:Javascript 在Typescript中将int强制转换为枚举字符串,javascript,angular,typescript,enums,Javascript,Angular,Typescript,Enums,我从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, }
[
{
"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值。但我想得到一个字符串值
e、 g:
TypeScript中的枚举在运行时是数字,因此
消息。type
将是0
、1
、2
或3
要获取字符串值,需要将该数字作为索引传递到枚举中:
Type[0] // "Info"
因此,在您的示例中,您需要执行以下操作:
Type[message.type] // "Info" when message.type is 0
TypeScript中的枚举是运行时的对象,其属性从
int->string
开始,从string->int
开始,适用于所有可能的值
要访问字符串值,需要调用:
Type[0] // "Info"
但请确保将正确的类型传递到属性访问器,因为链接调用可能会导致以下结果:
Type[Type.Info] // "Info"
Type[Type[Type.Info]] // 0
Type["Info"] // 0
Type[0] // "Info"
我认为
{{message.type}}
您只获取映射值,而不是枚举。
请尝试以下代码
{{TYPE[message.type]}}
这是编译时问题还是运行时问题?它编译并运行良好。对于
{{message.type}]
我得到0
但我想得到Info
。我该怎么做?我现在正在这样映射:(response=>response.json()作为message[]
将type
导入文件,而不是执行message.type
获取值,执行键入[message.type]
。您可以在需要字符串值的位置执行此操作。不幸的是,Type
在模板中不可用,除非您将其作为属性添加到组件类中,作为public Type=Type;
。有人能告诉我为什么在我的情况下键入[message.Type]吗?在调试器中,我会看到一个错误,因为Type未定义(已正确导入此.ts文件)?如何检查数字是否是枚举的一部分,f.x。在返回类型[3000]之前检查数字3000?@gajo357您可以使用in
操作符测试3000,或者枚举中是否存在任何值/键。例如const has3000=3000 in Type
{{TYPE[message.type]}}