我正在使用Proxy()为简单的设置对象提供“修改时保存”。对象本身最终以类似于地图的简单对象的形式公开,因此对Settings.connectionString
的调用将返回JSON文件(或更高版本,Database)中的connectionString和诸如{{1 }},然后将更新后的connectionCount保存到数据库和本地对象。
我的初始值设定项(和定义)如下:
Settings.connectionCount = 2
如您所见,导出的Proxy对象会覆盖get()并设置为从Map()返回值,但是访问它会给我带来import * as fs from "fs";
import { EventEmitter } from "events";
// EventEmitter is so you can listen for the "SettingsLoaded" event rather than polling
class SettingsFactory extends EventEmitter {
public isLoaded:boolean = false;
public settings:Map<string, any>;
constructor() {
super();
// Initial load from file.
fs.readFile("settings.json", (err, data) => {
if (err) {
throw err;
}
const json = JSON.parse(data.toString());
for (const key in json) {
if (json.hasOwnProperty(key)) {
this.settings.set(key, json[key]);
}
}
// Database loading should go here, overriding the file values, but for now we can do without it.
this.isLoaded = true;
this.emit("SettingsLoaded", this);
});
}
}
const ProxiedSettings = new SettingsFactory();
// Doing this provides us with a singleton, which is nice.
export default new Proxy(ProxiedSettings, {
get: (target, name:string) => {
if (target.isLoaded) {
if (target.settings.has(name)) {
return target.settings.get(name);
} else {
return target[name];
}
} else {
throw new Error("Settings not loaded yet");
}
},
set: (target, name:string, value) => {
// update value
if (target.isLoaded) {
target.settings.set(name,value);
return true;
} else {
return false;
}
}
});
的错误。
我希望能够使用Property 'connectionString' does not exist on type 'SettingsFactory'
访问(获取/设置)Settings上的任意值,而if (!target.settings.has(name)) { return target[name]; }
允许访问EventEmitter的“ on”处理程序,但是现在我什至没有那么远。
关于如何告诉TypeScript这种情况下存在Settings["*"]
的任何想法?