Search code examples
angulartypescriptconstants

Define a global Typescript const file in Angular


I would like to create a global const file for my Angular project. Now after doing some research there are multiple ways of creating such:

  1. const class (readonly modifier doesn't work at runtime)
  2. const file (missing differentiation between multiple contexts)
  3. environment files (only for environment-specific use cases)

But each seem to have some downsides as mentioned above.

Now I just tried it anyway with the const file. But only with a single big const object. Simliar to Angular environment files. Now to make it unmutable I added the Readonly type as well as the Object.freeze function to it:

export const constants: Readonly<any> = Object.freeze({
  Context:
    {
      PI: 3.14159265359,
      WEATHER: 'https://goweather.herokuapp.com/weather/',
    },
   AnotherContext: {...}
})

Would this be the right approach or am I still missing some points here? Thank you!


Solution

  • You select the right option - have separate file with exported const(s). Just for typescript you have better option to write it. Use as const to make each property of the object readonly:

    export const constants = {
      Context:
        {
          PI: 3.14159265359,
          WEATHER: 'https://goweather.herokuapp.com/weather/',
        },
       AnotherContext: {...}
    } as const;
    

    You can read more about how it works here