From 6c3f0d2b1d890954a61c3b168853b853b8e929c7 Mon Sep 17 00:00:00 2001 From: Jan Molak <1089173+jan-molak@users.noreply.github.com> Date: Sun, 5 Jun 2022 23:00:08 +0100 Subject: [PATCH] fix(tinytype): toJSON correctly serialises null and undefined values --- spec/TinyType.spec.ts | 20 ++++++++++++++++++++ src/TinyType.ts | 11 +++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/spec/TinyType.spec.ts b/spec/TinyType.spec.ts index 1e585f22..5ee7fd62 100644 --- a/spec/TinyType.spec.ts +++ b/spec/TinyType.spec.ts @@ -327,6 +327,26 @@ describe('TinyType', () => { }); }); + it('should serialise null and undefined', () => { + interface NotesType { + nullValue: any; + undefinedValue: any; + } + + class Notes extends TinyTypeOf() { + } + + const notes = new Notes({ + nullValue: null, + undefinedValue: undefined, + }); + + expect(notes.toJSON()).to.deep.equal({ + nullValue: null, + undefinedValue: undefined, + }); + }); + it(`should JSON.stringify any object that can't be represented in a more sensible way`, () => { class TT extends TinyTypeOf() { } diff --git a/src/TinyType.ts b/src/TinyType.ts index dae08471..4ca9d69c 100644 --- a/src/TinyType.ts +++ b/src/TinyType.ts @@ -178,6 +178,13 @@ function isSerialisableNumber(value: unknown): value is number { } function isSerialisablePrimitive(value: unknown): value is string | boolean | number | null | undefined { - return ['string', 'boolean', 'null', 'undefined'].includes(typeof value) - || isSerialisableNumber(value); + if (['string', 'boolean'].includes(typeof value)) { + return true; + } + + if (value === null || value === undefined) { + return true; + } + + return isSerialisableNumber(value); }