I am trying to refactor an unwieldy config interface/object by separating its various sections into separate files under a namespace I've cleverly named Config.
The documentation talks about namespaces that span multiple files and declaration merging of interfaces, but I can't seem to get them to work together.
src/config/index.ts
/// <reference path="./server.ts" />
import fs from 'fs';
import json5 from 'json5';
const _config = readConfig();
namespace Config {
export const config = _config;
export interface IConfig {
someGeneralProperty: {
// ...
}
}
}
function readConfig(): Config.IConfig {
return json5.parse(fs.readFileSync('./path/to/config.json', 'utf-8'));
}
function doSomeOtherStuff() {
// fails: Property 'server' does not exist on type 'IConfig'.
console.log(_config.server.host);
}
src/config/server.ts
/// <reference path="./index.ts" />
namespace Config {
export interface IConfig {
server: {
host: string;
port: number;
}
}
}
src/index.ts
// fails: Module '"./config"' has no exported member 'config'.
import { config } from './config';
// fails: Cannot use namespace 'Config' as a value.
// fails: Namespace 'Config' has no exported member 'config'.
import config = Config.config;
I've tried several variations of exporting things, such as export default Config;, export namespace Config {...} in each of the src/config/... files, changing export const config to export var config. In src/config/index.ts I tried export * from './server'. Nothing seems to help.
I have a feeling I'm just going about this all wrong.
Oddly, the interfaces within the namespace in every file are exported from the namespace, so in src/index.ts, I can do:
import IConfig = Config.IConfig;
let c: IConfig;
console.log(c.server.host);
but I cannot do that in either src/config/index.ts nor src/config/server.ts.
/// <reference path="Validation.ts" />and then they use the namespacelet validators: { [s: string]: Validation.StringValidator; } = {};There is no import mentioned. I think you should use it same way, do the reference/// <reference path="./index.ts" />instead of import and then you should be able to useConfig.configI didnt test it so I do not post it as an answer. But might be worth trying.