Typescript Export enum based on the condition?

旧巷老猫 提交于 2021-02-10 14:21:01

问题


Angular based on the environment I need to export enum. I don't know wether it is correct or not? role.ts

import { environment } from '../../environments/environment';
if(environment.production) {
  export enum Role {
   User: 'user',
   Admin: 'admin'
  }
 } else {
  export enum Role {
   User: 'user',
   Admin: 'user'
  }
}

Based on the condidtion how to export it? Thanks


回答1:


You can do it like this:

import { environment } from '../../environments/environment';
export class Role {
  static User = 'user';
  static Role = (environment.production) ? 'role' : 'admin';
}



回答2:


String emuns like:

    export enum Role {
       User = 'user',
       Admin = 'admin',
   }

Will be built into:

     "use strict";
   Object.defineProperty(exports, "__esModule", { value: true });
   var Role;
   (function (Role) {
       Role["User"] = "user";
       Role["Admin"] = "admin";
   })(Role = exports.Role || (exports.Role = {}));

So as you can see in the end your enum would be an object. You can rewrite your code like this

  import { environment } from '../environments/environment';

    export const Roles = getRole();

    function getRole() {
     if (environment.production) {
       return {
         User: 'user',
         Admin: 'admin'
       };
     }

     return {
       User: 'user',
       Admin: 'user'
     };
    }


来源:https://stackoverflow.com/questions/58595158/typescript-export-enum-based-on-the-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!