JSON 转 TypeScript interface:嵌套对象自动展开
真实接口 JSON 几乎都有嵌套:用户里有地址,地址里有省市。手动写这些嵌套 interface 既繁琐又容易漏。工具会递归展开每一层。
嵌套示例
{
"id": 1024,
"name": "Ada Lovelace",
"active": true,
"tags": ["math", "computing"],
"profile": { "city": "London", "followers": 1200 },
"scores": [98.5, 87, 91]
}
自动展开为:
export interface Root {
id: number;
name: string;
active: boolean;
tags: string[];
profile: {
city: string;
followers: number;
};
scores: number[];
}
小技巧
- 把根类型名改成你的业务名(如
UserResp)更易读。 - 数组字段会推导为
T[],无需手写。
常见问题
能改根类型名吗?
可以,生成后把 Root 改成你需要的名字即可,结构不受影响。
空数组会生成什么?
空数组会推导出 any[],建议补一条样本数据以获得更精确的类型。
相关阅读