JavaScriptFundamental (ES6), part 2
Proxy ownKeys invariants in JavaScript
61 ownKeys has to agree with getOwnPropertyDescriptor
hardWrite an ownKeys trap that invents a key the target does not have. Find out why Reflect.ownKeys lists it and Object.keys does not, then make them agree. Then break three of the invariants the engine enforces and confirm each one throws.
Stuck? Three hints, smallest first
- 1.
Object.keysfilters the reported keys by asking for each one's descriptor, and drops any that has none. - 2. So the fix is a
getOwnPropertyDescriptortrap that describes the invented key. - 3. The engine refuses three things outright: duplicates, hiding a non-configurable key, and inventing a key on a non-extensible target.
const attemptName = (fn) => { try { fn(); return 'no error'; } catch (err) { return err.name; } };
const base = { stop: 'Ojota' };
// An invented key, reported by ownKeys but described by nobody.
const halfDone = new Proxy(base, {
ownKeys: (t) => [...Reflect.ownKeys(t), 'zone'],
});
const reflectSees = Reflect.ownKeys(halfDone);
const objectKeysSees = Object.keys(halfDone);
const spreadSees = Object.keys({ ...halfDone });
// The same trap, with a descriptor for the invented key.
const consistent = new Proxy(base, {
ownKeys: (t) => [...Reflect.ownKeys(t), 'zone'],
getOwnPropertyDescriptor(t, key) {
if (key === 'zone') return { value: 'Lagos Mainland', enumerable: true, configurable: true };
return Reflect.getOwnPropertyDescriptor(t, key);
},
get(t, key, r) { return key === 'zone' ? 'Lagos Mainland' : Reflect.get(t, key, r); },
});
const nowKeys = Object.keys(consistent);
const nowSpread = { ...consistent };
// Invariant 1: no duplicates.
const duplicated = new Proxy({}, { ownKeys: () => ['stop', 'stop'] });
const duplicateError = attemptName(() => Reflect.ownKeys(duplicated));
// Invariant 2: a non-configurable own key cannot be hidden.
const pinned = {};
Object.defineProperty(pinned, 'id', { value: 'LAG-0061', configurable: false, enumerable: true });
const hiding = new Proxy(pinned, { ownKeys: () => [] });
const hidingError = attemptName(() => Reflect.ownKeys(hiding));
// Invariant 3: nothing may be invented on a non-extensible target.
const sealedTarget = Object.preventExtensions({ stop: 'Ojota' });
const inventing = new Proxy(sealedTarget, { ownKeys: (t) => [...Reflect.ownKeys(t), 'zone'] });
const inventingError = attemptName(() => Reflect.ownKeys(inventing));
console.log('Reflect vs Object.keys:', reflectSees, objectKeysSees);
console.log('once consistent :', nowKeys, nowSpread);
console.log('invariant errors :', [duplicateError, hidingError, inventingError]);
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('Reflect.ownKeys reports exactly what the trap returned', reflectSees, ['stop', 'zone']);
test('Object.keys drops the invented key, because nothing describes it', objectKeysSees, ['stop']);
test('and spread drops it for the same reason', spreadSees, ['stop']);
test('adding a getOwnPropertyDescriptor trap makes them agree', nowKeys, ['stop', 'zone']);
test('and then the key is copied out with its value', nowSpread, { stop: 'Ojota', zone: 'Lagos Mainland' });
test('a duplicate key in ownKeys is a TypeError', duplicateError, 'TypeError');
test('so is hiding a non-configurable own key', hidingError, 'TypeError');
test('so is inventing a key on a non-extensible target', inventingError, 'TypeError');
Object.keys is not ownKeys. It calls [[OwnPropertyKeys]] and then, for each string key, asks [[GetOwnProperty]] whether that property is enumerable. A key with no descriptor is not enumerable, so it is filtered out — which is why the first proxy is listed one way by Reflect.ownKeys and another by everything a normal program uses. Two traps, one story: report a key and you must describe it.
The invariants are the part worth internalising, because they are the boundary of what a proxy is allowed to lie about. A proxy may not contradict facts a caller could already have relied on: something told a key is non-configurable can never be told it is gone, and something told an object is non-extensible can never be shown a new key. Break either and the engine throws a TypeError at the caller, from a line that looks entirely innocent. Duplicates are rejected outright because the result is meant to be a set of keys.
One more invariant lurks in the descriptor trap above: it reports configurable: true. Reporting a property as configurable: false when the target has no such property is also a TypeError, for the same reason — it is a promise about an object that cannot keep it. When in doubt, describe invented properties as configurable and enumerable, and let the target speak for its own.