把 JSON 转成 TypeScript Interface,本质上是从一份真实数据样本里推断字段名、字段类型和嵌套结构。
前端接接口时,经常会先拿到一段返回 JSON,再手写对应的 TypeScript 类型。字段少的时候还好,字段一多、嵌套一深,就很容易漏字段、写错数组类型,或者把可能为 null 的值误写成 string。
一个简单例子
{
"id": 1001,
"name": "ToolGarden",
"active": true,
"tags": ["json", "typescript"],
"profile": {
"score": 98.5,
"city": null
}
}这段 JSON 可以推断出根对象、嵌套 profile 对象、字符串数组 tags,以及 null 字段 city。
interface Root {
id: number;
name: string;
active: boolean;
tags: string[];
profile: Profile;
}
interface Profile {
score: number;
city: null;
}类型推断通常怎么判断?
| JSON 值 | TypeScript 类型 | 说明 |
|---|---|---|
| 字符串 | string | 例如 name、email、url |
| 数字 | number | TypeScript 不区分 int 和 float |
| true / false | boolean | 适合状态字段 |
| 数组 | T[] | 根据数组元素继续推断 |
| 对象 | interface | 嵌套对象通常会生成新接口 |
| null | null 或联合类型 | 如果样本不足,需要人工确认是否还可能是 string 或 number |
生成后还要检查哪些地方?
- 数组为空时无法知道元素类型,需要补充更完整的样本。
- 同一字段有时是字符串、有时是 null,应改成联合类型,例如 string | null。
- 接口命名最好和业务语义一致,不要全部保留 Root、Item 这类临时名字。
- 日期字符串通常仍然是 string,不要直接当成 Date,除非代码里会主动转换。
总结
自动生成 interface 适合做第一版类型草稿。真正用于项目时,建议再根据接口文档和业务规则检查可选字段、null、枚举值和命名。