0

I am a Java developer, when I want to avoid hardcode values directly in the code, sometimes I create a 'tree' of values like this:

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]
}

I recently moved to Typescript and I want to keep this good practice of avoiding write literals onto my code.

Sometimes I have been used enums but right now I need to write values inside other values to represent the properties of a json configuration file.

What is the correct equivalent in Typescript to do this?

svprdga
  • 2,171
  • 1
  • 28
  • 51

2 Answers2

2

You can define a similar structure in Typescript, although this approach does not seem very Typescript oriented:

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

If you don't want to use enums, this might be a better option:

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
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
0

Using classes inside classes its ok, but I got lint warnings, I ended up using namespaces and works for me:

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]
}
svprdga
  • 2,171
  • 1
  • 28
  • 51