简体   繁体   中英

TypeScript: 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 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM