TypeScript:如何建模 json 对象

2024-04-20

我想输入一个变量,该变量应该是能够使用 JSON.stringify 序列化的对象。

我找到了这个定义 https://github.com/Microsoft/TypeScript/issues/15225#issuecomment-294718709但我想知道是否有一些内置类型,或者更好的方法来做到这一点:

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

在我看来,这应该是很常见的事情。


没有内置类型 https://github.com/microsoft/TypeScript/issues/1897,但从 Typescript 3.7 开始可以简化为:

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

有关递归类型别名的更多信息here https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#more-recursive-type-aliases.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

TypeScript:如何建模 json 对象 的相关文章

随机推荐