1.2.4 • Published 3 years ago
@kidonng/typed-json v1.2.4
typed-json
Better typed
JSON.parseandJSON.stringify
Install
npm install @kidonng/typed-jsonUsage
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')) // => neverMotivation
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.parsereturn values - Developers may mistakenly pass a non-serializable value to
JSON.stringify
With typed-json:
JSON.parsereturnsJsonValuewhich matches any valid JSON value and enables type checking.JSON.stringifyreturnsneverif the value can not beJsonifyand 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`
})