如何在打字稿中检查类型是否为枚举 [英] How to check the type is enum or not in typescript

查看:80
本文介绍了如何在打字稿中检查类型是否为枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串枚举类型,例如:

I have a string enum type like:

export enum UserRole {
admin = "admin",
active = "active",
blocked = "blocked"
}

我想检查某些字符串是emule还是不怎么做?

I want to check certain string is emule or not how to do it?

  const djson = JSON.parse(decode_string)
  if(djson && (djson.role instanceof UserRole) // I just want to check the role is enum string or not. Obviously  this way is wrong.

该怎么做?

推荐答案

Javascript没有枚举的概念,因此不可能。在编译时,打字稿将枚举定义转换为您日常使用的普通Javascript对象。

Javascript does not have the concept of Enum so it's not possible, When compiling, typescript translates the enum definition to normal Javascript object that you use everyday. No information about Enum is reserved for you to inspect.

因此下面的此枚举定义

enum UserRole {
    admin = "admin",
    active = "active",
    blocked = "blocked"
}

将被翻译成这样

var UserRole;
(function (UserRole) {
    UserRole["admin"] = "admin";
    UserRole["active"] = "active";
    UserRole["blocked"] = "blocked";
})(UserRole || (UserRole = {}));

这篇关于如何在打字稿中检查类型是否为枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆