Skip to content

Commit

Permalink
feat: throw for excess keys in objects
Browse files Browse the repository at this point in the history
  • Loading branch information
StyleShit committed Jul 13, 2024
1 parent 907b9c1 commit b6ce629
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/serious-crews-eat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'bodek': patch
---

Throw for excess keys in objects
9 changes: 9 additions & 0 deletions src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,15 @@ describe('Bodek', () => {

// Assert - invalid.
expect(() => schema.parse({ foo: 'hello' })).toThrow('Missing key bar');

expect(() =>
schema.parse({
foo: 'hello',
bar: 123,
nested: { baz: 'world' },
extra: true,
}),
).toThrow('Unexpected excess key extra');
});

it('should infer types', () => {
Expand Down
6 changes: 6 additions & 0 deletions src/schemas/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ export class ObjectSchema<Shape extends ShapeSchema> extends Schema<
schema.parse(value[key as never]);
});

Object.keys(value).forEach((key) => {
if (!(key in this.shape)) {
throw new Error(`Unexpected excess key ${key}`);
}
});

return value as never;
}
}

0 comments on commit b6ce629

Please sign in to comment.