Proxy Target Type Flows Into Traps
New Proxy over a typed target hands every trap the target type, so keyof guards decide what can be indexed and reads log through one place.
Code
// Proxy<FeatureFlags>: the target type flows into every trap signature.
interface FeatureFlags {
darkMode: boolean;
betaSearch: boolean;
}
const source: FeatureFlags = { darkMode: true, betaSearch: false };
const flags = new Proxy<FeatureFlags>({ ...source }, {
get(target, property, receiver) {
// property is string | symbol; narrow with keyof before indexing
if (typeof property === 'string' && property in target) {
const key = property as keyof FeatureFlags;
console.log(`read ${key}: ${String(target[key])}`);
return target[key];
}
return undefined;
},
});
console.log('value darkMode:', flags.darkMode);
console.log('value betaSearch:', flags.betaSearch);
// Writes land on the proxied object itself, so reads after writes agree
flags.betaSearch = true;
console.log('after write:', flags.betaSearch);Output
Captured from a sandboxed run of this snippet in the build pipeline.
read darkMode: true
value darkMode: true
read betaSearch: false
value betaSearch: false
read betaSearch: true
after write: trueHow it works
All the work happens on the top-level bindings: flags.
The top-level object literal pins darkMode, betaSearch as plain values — no derivation, no imports behind them.
What to watch for
- Self-sufficient by design — there is no registry and no lockfile entry.
Putting it to use
Each step the file takes is announced in the output: read $, value darkMode:, value betaSearch:.
Core lines
const key = property as keyof FeatureFlags;
return target[key];
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. Its state lives in module-level bindings: `flags`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.