JSON转TypeScript
从JSON生成TypeScript接口
JSON输入
TypeScript输出
什么是JSON转TypeScript转换?
粘贴JSON数据,即可获得TypeScript接口——这些类型化契约精确描述了对象拥有哪些属性以及每个属性的类型。若没有接口,JSON.parse()返回的数据类型为any,在属性访问或赋值时既无编辑器提示,也无编译器检查。将JSON转换为TypeScript,无需手动编写接口即可获得这种类型安全保障。
TypeScript涵盖所有六种JSON值类型:string、number、boolean、null、object和array。每个嵌套的JSON对象都会生成独立的命名接口。数组类型从第一个元素推断。生成结果与JSON.parse()在运行时的实际返回值一致,因此接口反映的是真实数据,而非猜测。
对于大型或深度嵌套的JSON,手动编写接口既繁琐又容易出错。JSON转TypeScript生成器可自动读取结构、递归处理嵌套,并在几秒内输出整洁的接口代码。这在对接陌生API、使用模拟数据原型开发,或将JavaScript代码库迁移至TypeScript时尤为有用。它还能省去手动追踪嵌套属性名称和类型的工作,让你专注于业务逻辑,而非类型模板代码。
为什么使用JSON转TypeScript生成器?
手动生成TypeScript接口在对象较小时尚可,但面对嵌套结构或大型API响应时很快就会力不从心。设想一个拥有三层嵌套的50字段API响应——手动编写意味着数十个接口,每一个都可能存在拼写错误或遗漏可空字段的问题。自动生成器在毫秒内生成完整接口集,并降低代码与所消费数据之间发生类型不匹配的风险。除准确性外,它还能让类型与实际API契约保持同步。当服务更改响应结构时,只需粘贴更新后的JSON重新生成即可,远比在手写接口文件中逐一查找每个变动的属性快得多。
JSON转TypeScript使用场景
JSON到TypeScript类型映射参考
每种JSON值都映射到一种TypeScript类型。下表展示各JSON原始类型和结构类型的对应关系。该映射遵循ECMA-404 JSON标准和TypeScript内置类型。
| JSON类型 | 示例值 | TypeScript类型 |
|---|---|---|
| string | "hello" | string |
| number | 42, 3.14 | number |
| boolean | true, false | boolean |
| null | null | null |
| object | {"key": "value"} | nested interface |
| array | [1, 2, 3] | number[] (inferred from first element) |
TypeScript interface与type别名的区别
TypeScript提供两种描述对象结构的方式:interface声明和type别名。两者都能表示JSON结构,但在扩展和合并行为上有所不同。大多数JSON转TypeScript生成器输出interface,因为它是TypeScript中描述对象结构的惯用选择。
代码示例
以下示例展示如何在不同语言和工具中从JSON生成TypeScript接口,每段代码均可直接运行。
// Manual interface definition from a JSON shape
const json = '{"id": 1, "name": "Alice", "active": true}';
const parsed = JSON.parse(json);
interface User {
id: number;
name: string;
active: boolean;
}
const user: User = parsed;
console.log(user.name); // "Alice" — fully typedimport JsonToTS from 'json-to-ts';
const json = {
id: 1,
name: "Alice",
address: { street: "123 Main St", city: "Springfield" },
tags: ["admin", "user"]
};
const interfaces = JsonToTS(json, { rootName: "User" });
console.log(interfaces.join("\n\n"));
// interface Address {
// street: string;
// city: string;
// }
//
// interface User {
// id: number;
// name: string;
// address: Address;
// tags: string[];
// }# Install: pip install datamodel-code-generator
# Generate TypeScript-style types from JSON using Pydantic models
# Command line:
# datamodel-codegen --input data.json --output model.py
# Or generate TypeScript directly with quicktype:
# pip install quicktype
# quicktype --lang ts --src data.json --out types.ts
import json
data = {"id": 1, "name": "Alice", "scores": [98, 85, 92]}
# Python equivalent using TypedDict (Python 3.8+)
from typing import TypedDict, List
class User(TypedDict):
id: int
name: str
scores: List[int]
user: User = data # type-checked by mypy# Install quicktype globally
npm install -g quicktype
# Generate TypeScript interfaces from a JSON file
quicktype --lang ts --src data.json --out types.ts
# From a JSON string via stdin
echo '{"id": 1, "name": "Alice"}' | quicktype --lang ts
# Output:
# export interface Root {
# id: number;
# name: string;
# }