Skip to content

Commit

Permalink
support serializing objects without prototype (#145)
Browse files Browse the repository at this point in the history
* add failing test

* consider null-prototype object a "plain" object

Co-authored-by: Simon Knott <info@simonknott.de>
  • Loading branch information
KATT and Skn0tt committed Aug 3, 2021
1 parent af5af55 commit e1a897c
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -936,3 +936,13 @@ test('regression #108: Error#stack should not be included by default', () => {
) as any;
expect(thatShouldExist).toEqual(input.stack);
});

test('regression: `Object.create(null)` / object without prototype', () => {
const input: Record<string, unknown> = Object.create(null);
input.date = new Date();

const stringified = SuperJSON.stringify(input);
const parsed: any = SuperJSON.parse(stringified);

expect(parsed.date).toBeInstanceOf(Date);
});
6 changes: 6 additions & 0 deletions src/is.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
isString,
isSymbol,
isUndefined,
isPlainObject,
} from './is';

test('Basic true tests', () => {
Expand Down Expand Up @@ -68,3 +69,8 @@ test('Primitive tests', () => {
test('Date exception', () => {
expect(isDate(new Date('_'))).toBe(false);
});

test('Regression: null-prototype object', () => {
expect(isPlainObject(Object.create(null))).toBe(true);
expect(isPrimitive(Object.create(null))).toBe(false);
});
1 change: 1 addition & 0 deletions src/is.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export const isPlainObject = (
payload: any
): payload is { [key: string]: any } => {
if (getType(payload) !== 'Object') return false;
if (Object.getPrototypeOf(payload) === null) return true;
return (
payload.constructor === Object &&
Object.getPrototypeOf(payload) === Object.prototype
Expand Down

0 comments on commit e1a897c

Please sign in to comment.