[ PROMPT_NODE_25016 ]
openapi-to-typescript
[ SKILL_DOCUMENTATION ]
# OpenAPI to TypeScript
将 OpenAPI 3.0 规范转换为 TypeScript 接口和类型守卫。
**输入:** OpenAPI 文件(JSON 或 YAML)
**输出:** 包含接口和类型守卫的 TypeScript 文件
## 何时使用
- "generate types from openapi"
- "convert openapi to typescript"
- "create API interfaces"
- "generate types from spec"
## 工作流
1. 请求 OpenAPI 文件路径(如果未提供)
2. 读取并验证文件(必须为 OpenAPI 3.0.x)
3. 从 `components/schemas` 中提取模式
4. 从 `paths` 中提取端点(请求/响应类型)
5. 生成 TypeScript(接口 + 类型守卫)
6. 询问保存位置(默认:当前目录下的 `types/api.ts`)
7. 写入文件
## OpenAPI 验证
处理前检查:
- 必须存在 "openapi" 字段且以 "3.0" 开头
- 必须存在 "paths" 字段
- 必须存在 "components.schemas" 字段(如果有类型)
如果无效,报告错误并停止。
## 类型映射
### 基本类型
| OpenAPI | TypeScript |
|-------------|--------------|
| `string` | `string` |
| `number` | `number` |
| `integer` | `number` |
| `boolean` | `boolean` |
| `null` | `null` |
### 格式修饰符
| 格式 | TypeScript |
|---------------|-------------------------|
| `uuid` | `string` (注释 UUID) |
| `date` | `string` (注释 date) |
| `date-time` | `string` (注释 ISO) |
| `email` | `string` (注释 email)|
| `uri` | `string` (注释 URI) |
### 复杂类型
**对象:**
typescript
// OpenAPI: type: object, properties: {id, name}, required: [id]
interface Example {
id: string; // required: no ?
name?: string; // optional: with ?
}
**数组:**
typescript
// OpenAPI: type: array, items: {type: string}
type Names = string[];
**枚举:**
typescript
// OpenAPI: type: string, enum: [active, draft]
type Status = "active" | "draft";
**oneOf (联合类型):**
typescript
// OpenAPI: oneOf: [{$ref: Cat}, {$ref: Dog}]
type Pet = Cat | Dog;
**allOf (交叉类型/扩展):**
typescript
// OpenAPI: allOf: [{$ref: Base}, {type: object, properties: ...}]
interface Extended extends Base {
extraField: string;
}
## 代码生成
### 文件头
typescript
/**
* Auto-generated from: {source_file}
* Generated at: {timestamp}
*
* DO NOT EDIT MANUALLY - Regenerate from OpenAPI schema
*/
### 接口(来自 components/schemas)
对于 `components/schemas` 中的每个模式: