From 2b12d17e4ee91c01bc3ac40da21bde80466dfbbd Mon Sep 17 00:00:00 2001 From: Patrick McLaughlin Date: Wed, 10 Apr 2024 14:57:36 -0400 Subject: [PATCH] fix: make undefined behavior of optionalized work like partial --- packages/io-ts-http/src/combinators.ts | 4 ++++ packages/io-ts-http/test/combinators.test.ts | 6 ++++++ 2 files changed, 10 insertions(+) diff --git a/packages/io-ts-http/src/combinators.ts b/packages/io-ts-http/src/combinators.ts index 7f3f5f34..4c67aa28 100644 --- a/packages/io-ts-http/src/combinators.ts +++ b/packages/io-ts-http/src/combinators.ts @@ -43,6 +43,10 @@ const partialWithoutUndefined =

( }, (a) => { const result = partialCodec.encode(a); + if (result === undefined) { + // `t.partial` will return this when passed `undefined` even though it is not in the type + return result; + } for (const key of Object.keys(result)) { if (result[key] === void 0) { delete result[key]; diff --git a/packages/io-ts-http/test/combinators.test.ts b/packages/io-ts-http/test/combinators.test.ts index 295bb4ad..af67f106 100644 --- a/packages/io-ts-http/test/combinators.test.ts +++ b/packages/io-ts-http/test/combinators.test.ts @@ -113,6 +113,12 @@ describe('optionalized', () => { assertEncodes(optionalCodec, { a: undefined, b: 'foo' }, expected); }); + it('returns undefined when encoding undefined', () => { + const optionalCodec = c.optionalized({}); + const expected = undefined; + assertEncodes(optionalCodec, undefined, expected); + }); + it('decodes explicit null properties', () => { const nullCodec = c.optionalized({ a: t.null,