TypeScript: how to model a json object

Viewed 217

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

I found this definition but I wonder if there's some built in type, or a better way to do it:

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

It seems to me like it should be something pretty common.

1 Answers

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.

Related