I’m pretty new to TypeScript, and I’m trying to build a local app that will have some configuration stored in a TOML file. This configuration information will be used in different parts of the app and in different TypeScript files. What is the TypeScript idiomatic to share this with all the parts of the code that need it? Some of the code will need to use async/await
so I don’t think I can just pass it around as a function argument.
I’m not sure what is necessarily considered idiomatic in TypeScript but this sounds like a good use case for the Singleton pattern. Basically, you create a class that has an instance of itself as a member, then you set the constructor to private
so that new instances of the object cannot be created outside of the class itself. Finally, you add a static method that returns the instance stored within the class (or creates one if it does not exist already). For example:
class Config {
private static configInstance : Config;
prop1 : string
prop2 : string
private constructor() {
this.prop1 = 'default value 1';
this.prop2 = 'default value 2';
}
static getInstance() : Config {
if (!Config.configInstance) {
Config.configInstance = new Config();
}
return Config.configInstance;
}
}
// read your file here
let config = Config.getInstance();
console.log(config.prop1); // default value 1
config.prop1 = 'new value 1';
let config2 = Config.getInstance();
console.log(config2.prop1); // new value 1
You’ll read your config file when the program is first initializing, then use it to create your singleton Config object. Call getInstance()
when you need to access a config value, which should work within async code as well.