JSON to TypeScript
One input per line. Output is numbered to match the input order.
Pinned tools are listed in your favourites on the home page.Copies a link to this tool that carries your current input, so it opens ready to run.Gives you an iframe snippet for putting this tool on your own site.
Ctrl+Enter Run · Ctrl+Shift+C Copy · Esc Clear
Understand JSON to TypeScript
这个生成器读取一份 JSON 样本,写出描述其结构的 TypeScript 接口。
How it works
它遍历样本,并从每个键所对应的值推断类型:字符串变成 string,数字变成 number,嵌套对象成为各自独立的具名接口,数组则是元素类型后面跟上 []。推断能依据的例子只有这一个,因此输出精确描述的是这个例子——它是供你编辑的初稿,而不是由契约推导出的类型。
When to use it
- 为没有公布类型的第三方 API 响应编写类型。
- 把录制下来的载荷或测试夹具变成接口。
- 为一份庞大的嵌套响应得到初稿,而不必手工敲出来。
- 看清响应的真实结构,包括文档从未提及的字段。
Watch out for
- 一个恰好没有出现在样本中的可选字段会被生成为必填,而一个出现了但值为 null 的字段,则完全不能告诉生成器它真正的类型。请粘贴一份包含各种刁钻情况的样本,然后自行标注可选项。
- 所有数字都会变成 number。TypeScript 没有整数类型,因此 ID 与价格之间的区别就丢失了——而超过 2^53 的 ID 在 JSON 被解析时就已经丢了精度,那还在生成器看到它之前。
- 一个在不同响应中类型会变的字段——有时是字符串、有时是 null、有时是对象——会按你粘贴的那一版定型。生成的接口能通过编译,然后在运行时是错的。
Not the right tool for: 取代 schema。如果 API 发布了 OpenAPI 或 JSON Schema 文档,请从那里生成类型——它描述的是每一种响应,而不是其中的某一种。
Frequently Asked Questions
如何把 JSON 转换成 TypeScript 接口?
粘贴一份有代表性的 JSON 响应,并为根接口命名。类型会随你输入而生成:嵌套对象会成为各自独立的具名接口,数组按其元素定型,结果可直接粘进 .ts 文件或下载。
可选属性是如何识别的?
在一个对象数组中,只要有某一项缺少某个键,该键就会被标上问号成为可选。这也是为什么粘贴多条有代表性的记录,比只粘一条能得到更好的类型——生成器只能看到样本展示给它的东西。
null 值会怎样处理?
null 会被定型为 null 而不是靠猜测,因此一个既出现过数字又出现过 null 的键会变成 number | null。如果你的 API 用 null 表示「不存在」,可以打开「null 视为可选」,该键就会改为可选。
How to Use JSON to TypeScript
- Paste or type your input in the input area above.
- The tool processes your input automatically or click Run.
- Copy or download the result using the action buttons.
- Use Ctrl+Enter to run quickly from the keyboard.