代码之家  ›  专栏  ›  技术社区  ›  Shruggie

`JSON.stringfy中`value`的更强类型(value:any)`

  •  0
  • Shruggie  · 技术社区  · 2 年前

    官方TypeScript库 type definition 对于 value 的论点 JSON.stringify(value) any

    有更严格的类型吗 价值 这样序列化和反序列化会得到相同的值?换言之,以下情况属实:

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

    例如,如果 价值 Date 对象,则上述语句将为false。

    我要找的答案是

    type SerializableValue = ...
    
    2 回复  |  直到 2 年前
        1
  •  1
  •   Dimava    2 年前
    type JSONSerializeable = 
    | boolean
    | number
    | string
    | null
    | JSONSerializeable[]
    | Record<string, JSONSerializeable>
    

    从技术上讲,JSON可以序列化的东西更多,但以上就是它可以序列化的 取消序列化

    您可以使用

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

    my-global-types.d.ts 在您的项目中全局声明

        2
  •  1
  •   Shruggie    2 年前

    添加到Dimava的答案和这个 GitHub issue , type JSONValue 是最接近的:

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

    但是,仍然存在一些局限性:

    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
    
    推荐文章