Search code examples
jsontypescript

How to model a JSON object


I want to type a variable which should be an object capable of being serialized with JSON.stringify.

I found this definition:

export type JSONObject = { [key: string]: JSON }
export interface JSONArray extends Array<JSON> {}
export type JsonValue = null | string | number | boolean | JSONArray | JSONObject

but is there some built-in type, or a better way to do it?


Solution

  • No builtin type for this, but starting from Typescript 3.7 can be simplified to just:

    type Json = string | number | boolean | null | Json[] | { [key: string]: Json };
    

    More on recursive type aliases here.