Skip to content

Commit

Permalink
fix(tinytype): toJSON correctly serialises null and undefined values
Browse files Browse the repository at this point in the history
  • Loading branch information
jan-molak committed Jun 5, 2022
1 parent bcd4226 commit 6c3f0d2
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
20 changes: 20 additions & 0 deletions spec/TinyType.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,26 @@ describe('TinyType', () => {
});
});

it('should serialise null and undefined', () => {
interface NotesType {
nullValue: any;
undefinedValue: any;
}

class Notes extends TinyTypeOf<NotesType>() {
}

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<number>() {
}
Expand Down
11 changes: 9 additions & 2 deletions src/TinyType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}

0 comments on commit 6c3f0d2

Please sign in to comment.