Skip to content

Instantly share code, notes, and snippets.

@antoniusostermann
Created January 24, 2018 14:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antoniusostermann/a6cc1bb2056404682a827735b17df32a to your computer and use it in GitHub Desktop.
Save antoniusostermann/a6cc1bb2056404682a827735b17df32a to your computer and use it in GitHub Desktop.
An example of how to do configuration with typescript objects. Module developers have the possbility to define default values (which means they are optional for module users) and required values while module clients get only one simple interface to fulfill.
/** Users of your module possibly never need interfaces in this namespace. But you will. */
export namespace Configuration {
/** Configuration defaults -> all of these keys are optional for users of your module. */
export interface Defaults {
/** If set to true, my module will always fail. Default = false */
alwaysFail: boolean;
}
/** Required configuration options, no defaults are used here */
export interface Required {
/** Connection string of the database */
connectionString: string;
/** API key */
apiKey: string;
}
/** This is the interface you - as the module developer - are working with*/
export interface Runtime extends Defaults, Required {};
};
/** This is the interface for your module clients */
export interface Configuration extends Partial<Configuration.Defaults>, Configuration.Required {};
// Now you can do this in your own module code to set your defaults:
const myConfigurationDefaults: Configuration.Defaults = {
alwaysFail: false
};
// If you want to access configuration keys, use the Configuration.Runtime interface,
// which contains all user-required keys + your defaults/his or her overrides
const fullConfigurationSet: Configuration.Runtime = getConfiguration();
const fullConfigurationSet.alwaysFail; // no "possibly undefined" warning -> which is correct since we are applying defaults
// All of your clients can use the Configuration interface
import { Configuartion } from "your-module";
let myConfiguration: Configuration;
myConfiguration = {}; // illegal: missing properties "connectionString" and "apiKey"
myConfiguration = {connectionString: "host:port", apiKey: "dummy-key"}; // allowed
myConfiguration = {connectionString: "host:port", apiKey: "dummy-key", alwaysFail: true}; // allowed
myConfiguration = {connectionString: "host:port", apiKey: "dummy-key", alwaysFail: true, unknownOption: "unknown"}; // illegal: unknown key "unknownOption"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment