本工具读取一个 JSON 值,并为它写出 TypeScript interface 声明。key 完全保持原样;对象数组会合并成一个 interface,只在部分元素中出现的 key 会加上 ?,混合类型的值会变成联合类型。
可以用它为前端的 fetch 或 axios 响应添加类型,为 Next.js API 路由或 Express 处理函数声明返回类型,或者在后端只提供了示例响应而没有类型定义时使用。
类型名 中输入根 interface 的名称(例如 ChannelHistory);它会以 ?name= 的形式保存在 URL 中。types.ts 之类的文件中,然后通过 import type { ChannelHistory } from "./types" 使用。{
"channel": "general",
"messages": [
{ "id": "m1", "user": "kim", "text": "deploy done", "reactions": ["+1"] },
{ "id": "m2", "user": "lee", "text": null, "edited": true, "attachment": { "type": "image", "url": "https://cdn.example.com/a.png" } }
],
"cursor": 42
}export interface ChannelHistory {
channel: string;
messages: Message[];
cursor: number;
}
export interface Message {
id: string;
user: string;
text: string | null;
reactions?: string[];
edited?: boolean;
attachment?: Attachment;
}
export interface Attachment {
type: string;
url: string;
}
两条消息合并成了一个 Message interface;reactions、edited 和 attachment 只出现在其中一条里,所以加上了 ?。text 混有字符串和 null,得到 string | null。元素的 interface 名取 key 的单数形式(messages → Message)。
export interface,可以直接在别处导入。"a-b"、"2fa")会加上引号。?:)。string | number);null 以 | null 追加在最后。混合数组变成 (string | number)[]。unknown[]。export type Root = RootItem[]; 这样的别名。把类型作为泛型参数传入,例如 const res = await axios.get<ChannelHistory>(url),编辑器就会提醒你 res.data.messages[0].text 可能是 null。
对于没有 SDK 或 @types 包的内部或外部 API,一份示例响应就足以生成可在团队中共享的类型定义文件。
根据 Storybook 或测试用的 mock JSON 生成 interface,并用作组件 props 的类型;当 mock 与组件对不上时,编译器会告诉你。
number(不区分整数和浮点数),日期字符串是 string。"status": "active" 这类取值固定的字段会输出为 string;请自行收窄为字面量联合类型("active" | "banned")。Profile2。type 别名而不是 interface 吗?只有顶层为数组或基本类型时才使用 type 别名;对象始终是 interface。把 export interface X { ... } 改写成 export type X = { ... };,在这里的用途上效果相同。
?)和 | null 要分开?两者含义不同:? 表示 key 可能不存在(undefined),| null 表示 key 存在但值为 null。开启 strictNullChecks 后,这两种情况要分别处理。
TypeScript 类型描述的是实际的对象,改名后的 key 就和响应对不上了。如果代码中想用 camelCase,请为映射函数的结果另外定义一个类型。
本页只输出普通的类型声明。顶部的 TypeORM、Sequelize 和 Mongoose 标签页可以根据同一份 JSON 生成实体和模型代码。