skip to Main Content

The official TypeScript lib type definition for the value argument to JSON.stringify(value) is any.

Is there a stricter type for value such that serializing and deserializing it would result the same value? In other words, such that the following were true:

deepEqual(value, JSON.parse(JSON.stringify(value)))

For example, if value were a Date object, the above statement would be false.

The answer I’m looking for is

type SerializableValue = ...

2

Answers


  1. Chosen as BEST ANSWER

    Adding to Dimava's answer and this GitHub issue, type JSONValue is the closest it gets:

    type JSONValue = string | number | boolean | null | JSONObject | JSONArray;
    
    // Helpers
    type JSONObject = { [member: string]: JSONValue };
    interface JSONArray extends Array<JSONValue> {}
    

    But, there are still some limitations:

    import { strict as assert } from 'node:assert';
    
    assert.deepEqual(NaN, JSON.parse(JSON.stringify(NaN))) // => false
    assert.deepEqual(Infinity, JSON.parse(JSON.stringify(Infinity))) // => false
    

  2. type JSONSerializeable = 
    | boolean
    | number
    | string
    | null
    | JSONSerializeable[]
    | Record<string, JSONSerializeable>
    

    Technically there are more things JSON can serialize, but the above is what it can deseriaize

    You may use

    export { }
    declare global {
      interface JSON {
        parse(text: string): JSONSerializeable
      }
    }
    
    let x = JSON.parse('{"foo":"bar"}')
    //  ^?
    // let x: JSONSerializeable
    

    in a my-global-types.d.ts in your project to declare it globally

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search