1.2.4 • Published 2 years ago

@kidonng/typed-json v1.2.4

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

typed-json

Better typed JSON.parse and JSON.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

TS Playground

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 returns JsonValue which matches any valid JSON value and enables type checking.
  • JSON.stringify returns never if the value can not be Jsonify 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`
})

TS Playground

See Also

1.2.4

2 years ago

1.2.3

2 years ago

1.2.2

2 years ago

1.2.1

3 years ago

1.2.0

3 years ago

1.1.0

3 years ago

1.0.0

3 years ago