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.

TypescriptConfig Management

Code

typescriptsnippet
26 lines
// 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: true

How 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

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches. Its state lives in module-level bindings: `flags`.