【问题标题】:Tree structure of values: avoid hardcoded values in Typescript值的树结构:避免在 Typescript 中硬编码值
【发布时间】:2018-04-13 08:56:41
【问题描述】:

我是一名 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 中执行此操作的正确等效项是什么?

【问题讨论】:

    标签: typescript hardcode


    【解决方案1】:

    你可以在 Typescript 中定义一个类似的结构,虽然这种方法看起来不太面向 Typescript:

    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
    

    【讨论】:

      【解决方案2】:

      在类中使用类没问题,但我收到了 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]
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-05-01
        • 2011-01-07
        • 1970-01-01
        • 2022-10-31
        • 1970-01-01
        • 1970-01-01
        • 2011-01-01
        相关资源
        最近更新 更多