1.2.4 • Published 2 years ago
@kidonng/typed-json v1.2.4
typed-json
Better typed
JSON.parse
andJSON.stringify
Install
npm install @kidonng/typed-json
Usage
This is a type-only module and does not contain any runtime code.
import type {} from '@kidonng/typed-json'
JSON.parse('true') // => JsonValue
JSON.parse<boolean>('true') // => boolean
JSON.stringify({foo: 'bar'}) // => string
JSON.stringify(Symbol('foo')) // => never
Motivation
The built-in JSON
object is loosely typed by default:
interface JSON {
parse(text: string, reviver?: (this: any, key: string, value: any) => any): any;
stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;
stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;
}
This poses potential issues when using JSON.parse
and JSON.stringify
:
- Developers tend to forget type checking
JSON.parse
return values - Developers may mistakenly pass a non-serializable value to
JSON.stringify
With typed-json:
JSON.parse
returnsJsonValue
which matches any valid JSON value and enables type checking.JSON.stringify
returnsnever
if the value can not beJsonify
and prevents the result from being used.
typed-json also enforces stricter types when using the reviver
option of JSON.parse
, and replacer
option of JSON.stringify
:
import type {} from '@kidonng/typed-json'
JSON.parse('true', (key, value) => {
return value // `unknown`
}) // return `unknown` when using a reviver
JSON.stringify({foo: 'bar'}, (key, value) => {
return value // `unknown`
})