Skip to content

Commit 8a0cae5

Browse files
authored
chore: improve stringifyJSON in case toJSON exists (#643)
<!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Enhanced support for objects with custom `toJSON` methods in JSON stringification. - **Tests** - Added new test cases to verify correct handling of objects with `toJSON` methods returning `undefined`. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent 5b22383 commit 8a0cae5

File tree

3 files changed

+3
-1
lines changed

3 files changed

+3
-1
lines changed

packages/shared/src/json.test-d.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@ import { stringifyJSON } from './json'
33
it('stringifyJSON', () => {
44
expectTypeOf(stringifyJSON(undefined)).toEqualTypeOf<string | undefined>()
55
expectTypeOf(stringifyJSON({})).toEqualTypeOf<string>()
6+
expectTypeOf(stringifyJSON({ toJSON: () => undefined })).toEqualTypeOf<undefined | string>()
67
})

packages/shared/src/json.test.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ it('parseEmptyableJSON', () => {
1010

1111
it('stringifyJSON', () => {
1212
expect(stringifyJSON(undefined)).toBeUndefined()
13+
expect(stringifyJSON({ toJSON: () => undefined })).toBeUndefined()
1314
expect(stringifyJSON({})).toEqual('{}')
1415
expect(stringifyJSON({ foo: 'bar' })).toEqual('{"foo":"bar"}')
1516
})

packages/shared/src/json.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ export function parseEmptyableJSON(text: string | null | undefined): unknown {
66
return JSON.parse(text)
77
}
88

9-
export function stringifyJSON<T>(value: T): undefined extends T ? undefined | string : string {
9+
export function stringifyJSON<T>(value: T | { toJSON(): T }): undefined extends T ? undefined | string : string {
1010
// eslint-disable-next-line ban/ban
1111
return JSON.stringify(value)
1212
}

0 commit comments

Comments
 (0)