From b6ce6294f972d5f1690f0b335344cf9d1f65fed2 Mon Sep 17 00:00:00 2001 From: StyleShit Date: Sat, 13 Jul 2024 23:25:09 +0300 Subject: [PATCH] feat: throw for excess keys in objects --- .changeset/serious-crews-eat.md | 5 +++++ src/__tests__/index.test.ts | 9 +++++++++ src/schemas/object.ts | 6 ++++++ 3 files changed, 20 insertions(+) create mode 100644 .changeset/serious-crews-eat.md diff --git a/.changeset/serious-crews-eat.md b/.changeset/serious-crews-eat.md new file mode 100644 index 0000000..90fb2db --- /dev/null +++ b/.changeset/serious-crews-eat.md @@ -0,0 +1,5 @@ +--- +'bodek': patch +--- + +Throw for excess keys in objects diff --git a/src/__tests__/index.test.ts b/src/__tests__/index.test.ts index bd49e38..610a16b 100644 --- a/src/__tests__/index.test.ts +++ b/src/__tests__/index.test.ts @@ -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', () => { diff --git a/src/schemas/object.ts b/src/schemas/object.ts index 760b706..22f0374 100644 --- a/src/schemas/object.ts +++ b/src/schemas/object.ts @@ -35,6 +35,12 @@ export class ObjectSchema 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; } }