JSON 生成 TypeScript 类型:告别手敲 interface
TypeScript 的价值在于「编译期就能发现用错字段」。但很多团队的接口返回结构靠人工抄成 interface,字段一多就错位、漏改。<br><br>把 JSON 粘进来,点「生成 TS 类型」,工具会递归推导每一层对象的类型,直接产出可复用的 <code>interface</code>。
生成的 TypeScript 长什么样
同一段 JSON:
{
"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[];
}
在框架里怎么用
把生成的 interface 存成 types.ts,在请求层标注返回值类型,例如 const data = await res.json() as Root,之后 data.profile.city 就有完整提示,拼错字段会立刻飘红。
常见问题
嵌套对象会生成嵌套 interface 吗?
会。每一层 object 都会展开成对应的结构,数组元素类型也会正确推导为 T[]。
数字会区分 integer 和 number 吗?
TypeScript 里统一为 number,因为 TS 没有单独的 integer 类型,转换后对你的业务逻辑无损。
相关阅读