值的树结构:避免在Typescript中使用硬编码值

时间:2018-04-13 08:56:41

标签: typescript hardcode

我是一名Java开发人员,当我想直接在代码中避免使用硬编码值时,有时我会创建一个'树。像这样的价值观:

public class Values {

    public static final class Development {

        public static final class Environment {

            public static final String DEBUG = "debug";
            public static final String PRO_DEBUG = "pro_debug";
            public static final String TEST = "pre_release";
            public static final String AUTO_TEST = "auto_test";
            public static final String ALPHA = "alpha";
            public static final String RELEASE = "release";

        }
    }

    // [etc]
}

我最近转到了Typescript,我希望保持这种避免将写文字写入我的代码的良好做法。

有时候我使用了枚举,但是现在我需要在其他值中写入值来表示json配置文件的属性。

在Typescript中执行此操作的正确等价物是什么?

2 个答案:

答案 0 :(得分:2)

你可以在Typescript中定义一个类似的结构,虽然这种方法似乎不是面向Typecript的:

class Values {

    public static Development = class {

        public static Environment = class {

            public static readonly DEBUG = "debug";
            public static readonly PRO_DEBUG = "pro_debug";
            public static readonly TEST = "pre_release";
            public static readonly AUTO_TEST = "auto_test";
            public static readonly ALPHA = "alpha";
            public static readonly RELEASE = "release";

        }
    }
}

Values.Development.Environment.DEBUG

如果您不想使用枚举,这可能是更好的选择:

class Values {
    public static Development = Object.freeze({
        Environment :  Object.freeze({
            DEBUG : "debug",
            PRO_DEBUG : "pro_debug",
            TEST : "pre_release",
            AUTO_TEST : "auto_test",
            ALPHA : "alpha",
            RELEASE : "release"
        })
    })
}

Values.Development.Environment.DEBUG

答案 1 :(得分:0)

在类中使用类可以,但是我得到了lint警告,我最终使用名称空间并且为我工作:

export namespace Values {

  namespace Development {

      namespace Environment {

          const DEBUG = 'debug';
          const PRO_DEBUG = 'pro_debug';
          const TEST = 'pre_release';
          const AUTO_TEST = 'auto_test';
          const ALPHA = 'alpha';
          const RELEASE = 'release';

      }
  }

  // [etc]
}