将 JSON 转换为 TypeScript 接口是现代 Web 开发中最常见的任务之一。无论你是在使用 REST API、处理配置文件还是定义数据模型,拥有正确的 TypeScript 类型可以确保类型安全和更好的开发体验。
使用我们的免费工具即时将 JSON 转换为 TypeScript →
为什么要将 JSON 转换为 TypeScript?
TypeScript 的类型系统可以在编译时捕获那些本来会在运行时出现的错误。当你从 API 接收 JSON 时,TypeScript 并不知道数据的形状——除非你定义接口。没有类型,你将失去自动补全、重构支持和编译时错误检查。
- 自动补全——编辑器会建议有效的属性名
- 编译时错误——在部署前捕获拼写错误和缺少字段
- 自文档化代码——接口描述你的数据结构
- 重构安全——重命名字段时 TypeScript 会找到每个引用
基本转换规则
JSON 类型到 TypeScript 类型的基本映射非常直观:
| JSON 类型 | TypeScript 类型 | 示例 |
|---|---|---|
| string | string | "hello" |
| number (整数) | number | 42 |
| number (浮点数) | number | 3.14 |
| boolean | boolean | true |
| null | null | null |
| array | T[] | [1, 2, 3] |
| object | interface | {"key": "val"} |
// JSON
{
"name": "Alice",
"age": 30,
"active": true
}
// TypeScript
interface User {
name: string;
age: number;
active: boolean;
}处理嵌套对象
现实世界的 JSON 很少是扁平的。当对象包含其他对象时,应为每个层级创建单独的接口:
// JSON
{
"id": 1,
"name": "Alice",
"address": {
"street": "123 Main St",
"city": "Springfield",
"coordinates": {
"lat": 39.7817,
"lng": -89.6501
}
}
}
// TypeScript
interface Coordinates {
lat: number;
lng: number;
}
interface Address {
street: string;
city: string;
coordinates: Coordinates;
}
interface User {
id: number;
name: string;
address: Address;
}提示:使用独立的接口而不是深度嵌套的内联类型。这会使你的代码更可读、更可复用。
数组类型
JSON 中的数组可以包含统一或混合的类型。TypeScript 可以处理这两种情况:
// Uniform array
{ "tags": ["typescript", "react", "next"] }
// -> tags: string[]
// Array of objects
{
"users": [
{ "id": 1, "name": "Alice" },
{ "id": 2, "name": "Bob" }
]
}
// -> users: User[]
// Mixed array (rare but possible)
{ "data": [1, "two", true] }
// -> data: (number | string | boolean)[]当数组包含相同结构的对象时,定义一个专用接口。对于异构数组,使用联合类型。
Null 和可选字段
JSON API 通常对缺失值返回 null,或完全省略某些字段。TypeScript 区分这两种情况:
// JSON with null values
{
"id": 1,
"name": "Alice",
"avatar": null,
"bio": null
}
// TypeScript — nullable vs optional
interface User {
id: number;
name: string;
avatar: string | null; // field exists, value can be null
bio?: string; // field might not exist at all
nickname?: string | null; // might not exist OR might be null
}关键区别:null 表示字段存在但没有值。undefined(用 ? 标记为可选)表示字段可能根本不存在。对可空字段使用 | null,对可选字段使用 ?。
最佳实践
- 对象类型优先使用
interface而非type——接口可扩展且产生更好的错误信息 - 对 API 返回的不会修改的数据使用
readonly - 对真正动态的字段使用
unknown而非any——强制在使用前验证 - 清晰命名接口——使用
User,而不是IUser或UserInterface - 在中央
types/目录导出共享接口,便于项目中复用 - 运行时验证——TypeScript 类型在运行时会消失,使用 Zod 或 io-ts 等库进行 API 边界验证
// Good: runtime validation with Zod
import { z } from 'zod';
const UserSchema = z.object({
id: z.number(),
name: z.string(),
email: z.string().email(),
avatar: z.string().nullable(),
});
type User = z.infer<typeof UserSchema>;
// Validate API response
const user = UserSchema.parse(await res.json());自动化转换
为大型 JSON 负载手动编写接口既繁琐又容易出错。使用我们的 JSON to TypeScript 转换器,可以从任何 JSON 输入即时生成准确的接口。粘贴 JSON,获得 TypeScript——就是这么简单。