Skip to content

Commit

Permalink
Disallow shadowing.
Browse files Browse the repository at this point in the history
  • Loading branch information
danfuzz committed Nov 18, 2024
1 parent 99dc74d commit 1c425b3
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/structy/export/BaseStruct.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,9 @@ export class BaseStruct {
const disallowed = [];

for (const name of leftovers) {
if (this._impl_allowExtraProperty(name)) {
if (Reflect.has(this, name)) {
throw new Error(`Extra property would shadow pre-existing property: ${name}`);
} else if (this._impl_allowExtraProperty(name)) {
const value = this._impl_extraProperty(name, rawObject[name]);
if (value === undefined) {
throw new Error(`Extra property checker \`_impl_extraProperty()\` did not return a value. Maybe missing a \`return\`?`);
Expand Down
9 changes: 9 additions & 0 deletions src/structy/tests/BaseStruct.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,10 @@ describe('using a subclass which allows extra properties', () => {
class SomeStruct extends BaseStruct {
// @defaultConstructor

get yesNo() {
return 'maybe';
}

_impl_allowExtraProperty(name) {
return name.startsWith('yes');
}
Expand Down Expand Up @@ -370,5 +374,10 @@ describe('using a subclass which allows extra properties', () => {
const arg = { yesUndefined: 123 };
expect(() => new SomeStruct(arg)).toThrow(/did not return/);
});

test('throws given an extra property which would shadow a pre-existing property', () => {
const arg = { yesNo: 12345 };
expect(() => new SomeStruct(arg)).toThrow(/would shadow/);
});
});
});

0 comments on commit 1c425b3

Please sign in to comment.