refactor(types): 重构类型系统,统一共享类型定义

feat(types): 新增共享类型中心,包含用户、产品、订单等核心领域类型
fix(types): 修复类型定义错误,统一各模块类型引用
style(types): 优化类型文件格式和注释
docs(types): 更新类型文档和变更日志
test(types): 添加类型测试用例
build(types): 配置类型共享路径
chore(types): 清理重复类型定义文件
This commit is contained in:
2026-03-20 17:53:46 +08:00
parent 989c4b13a6
commit 427becbc8f
222 changed files with 25676 additions and 6328 deletions

View File

@@ -1,7 +1,7 @@
# AI文档索引
> **模块**: 05_AI - AI策略与规则
> **更新日期**: 2026-03-19
> **更新日期**: 2026-03-20
---
@@ -11,6 +11,35 @@
|------|------|------|
| [01_Strategy](01_Strategy.md) | AI策略设计 | ✅ |
| [02_Rules](02_Rules.md) | AI协作规则 | ✅ |
| [03_Implementation_Strategy](03_Implementation_Strategy.md) | AI实施策略 | ✅ |
| [04_Quick_Reference_Card](04_Quick_Reference_Card.md) | **AI开发快速参考卡片** | ✅ |
| [05_Development_Checklist](05_Development_Checklist.md) | **AI开发检查清单** | ✅ |
| [06_Wrong_vs_Right_Examples](06_Wrong_vs_Right_Examples.md) | **错误示例与正确示例对比** | ✅ |
| [07_TypeScript_Error_Fix_Guide](07_TypeScript_Error_Fix_Guide.md) | **TypeScript错误修复方案** | ✅ |
| [09_TypeScript_Error_Tasks](09_TypeScript_Error_Tasks.md) | **TypeScript错误任务列表** | 🔴 待领取 |
---
## AI 开发必读文档
### 开发前必读
1. **[快速参考卡片](04_Quick_Reference_Card.md)** - 硬性约束和代码模板
2. **[AI 开发规则](02_Rules.md)** - 逻辑集中化和禁止行为
3. **[项目硬性约束](../../.trae/rules/project-specific-rules.md)** - 自动加载的约束文件
### 开发中参考
1. **[TypeScript 编译规约](../01_Architecture/13_TypeScript_Standards.md)** - 类型安全规范
2. **[Schema 驱动开发](../01_Architecture/15_Schema_Driven_Development.md)** - 类型推导方法
3. **[统一类型管理](../01_Architecture/16_Unified_Type_Management.md)** - 类型中心架构
### 提交前检查
1. **[开发检查清单](05_Development_Checklist.md)** - 各阶段强制检查项
2. **[错误示例对比](06_Wrong_vs_Right_Examples.md)** - 避免常见错误
3. **[TypeScript 错误修复方案](07_TypeScript_Error_Fix_Guide.md)** - 解决 613 个编译错误
4. **[TypeScript 错误任务列表](09_TypeScript_Error_Tasks.md)** - AI 领取修复任务
---
@@ -23,4 +52,5 @@
## 最近更新
- 2026-03-20: 新增快速参考卡片、开发检查清单、错误示例对比、TypeScript错误修复方案文档
- 2026-03-19: 重构AI文档结构统一命名规范

View File

@@ -144,54 +144,45 @@
## 逻辑集中化强制规则
> **详细规范**: 详见 [项目规则 - 第8章](../../.trae/rules/project-specific-rules.md#8-逻辑集中化原则硬性约束)
### 核心原则
> **所有业务逻辑必须集中在 Service 层,禁止分散在 Controller、前端或数据库操作中。**
- 所有业务逻辑必须集中在 Service 层
- 禁止分散在 Controller、前端或数据库操作中
### AI开发强制规则
### AI开发强制规则(摘要)
1. **禁止在 Controller 中实现业务逻辑**
- Controller 只负责请求/响应和权限校验
- 业务决策、状态变化、数据校验必须在 Service
2. **禁止在前端实现业务规则**
- 前端只负责展示、交互和调用接口
- 禁止在前端进行业务计算、状态判断和权限判断
3. **禁止直接操作数据库**
- 所有数据库操作必须通过 Repository 层
- AI 不允许直接使用数据库连接或 ORM 操作数据库
4. **所有业务逻辑必须封装在 Service 层**
- 每个业务操作必须对应一个 Service 方法
- Service 方法必须体现业务闭环
5. **所有状态变更必须通过 Service 方法**
- 禁止直接修改状态字段
- 状态变更必须通过 Service 方法并遵循状态机
6. **所有跨模块操作必须在 Service 中完成**
- 跨模块协同必须在 Service 层实现
- 禁止在 Controller 或前端进行跨模块调用
7. **AI 修改代码时的优先顺序**
- 优先修改 Service 层代码
- 其次修改 Repository 层代码
- 最后修改 Controller 或前端代码
8. **Service 方法命名规范**
- 方法名必须体现业务闭环
- 例如:`createOrderWithInventoryLock()` 而不是 `createOrder()`
9. **状态机遵循**
- 所有状态变更必须遵循 STATE_MACHINE 定义
- 禁止非法状态流转
10. **服务层职责边界**
- Controller请求/响应 + 权限校验
- Service业务逻辑编排 + 状态流转 + 多模块协同
- Repository数据库 CRUD 操作
1. **禁止在 Controller 中实现业务逻辑** - Controller 只负责请求/响应和权限校验
2. **禁止在前端实现业务规则** - 前端只负责展示、交互和调用接口
3. **禁止直接操作数据库** - 所有数据库操作必须通过 Repository
4. **所有业务逻辑必须封装在 Service 层** - 每个业务操作必须对应一个 Service 方法
5. **所有状态变更必须通过 Service 方法** - 禁止直接修改状态字段
### 违反后果
- **代码审查不通过**:任何违反逻辑集中化原则的代码将被拒绝合并
- **AI 任务失败**AI 无法维护分散的逻辑,导致任务执行失败
- **生产环境风险**:分散逻辑导致数据不一致,直接影响系统稳定性
- **生产环境风险**:分散逻辑导致数据不一致,直接影响系统稳定性
---
## Mock 数据规范
> **详细规范**: 详见 [项目规则 - 第11章](../../.trae/rules/project-specific-rules.md#11-mock数据规范ai上下文安全)
### 核心原则
- **禁止**: 在业务组件中硬编码 Mock 数据
- **必须**: 通过 DataSource 抽象层获取数据
- **必须**: 所有 Mock 文件放在 `/mock` 目录
---
## TypeScript 编译错误修复
> **详细方案**: 详见 [TypeScript 错误修复方案](07_TypeScript_Error_Fix_Guide.md)
当前存在 613 个编译错误,必须按照分阶段策略修复:
1. **阶段 1**: 修复 tsconfig.json 配置
2. **阶段 2**: 消除所有 any 类型
3. **阶段 3**: 修复类型不匹配
4. **阶段 4**: 统一模块导入导出
5. **阶段 5**: 正确处理 undefined 和 null

View File

@@ -0,0 +1,342 @@
# AI 开发快速参考卡片AI Development Quick Reference Card
> **模块**: 05_AI - AI 开发快速参考
> **更新日期**: 2026-03-20
> **用途**: AI 开发时快速查阅的关键约束和规范
---
## 🔴 硬性约束(必须遵守)
### 1. TypeScript 类型安全
| 约束 | 说明 | 示例 |
|------|------|------|
| ❌ **禁止 any** | 使用 `unknown` + 类型守卫 | `function handle(data: unknown)` |
| ✅ **函数返回类型** | 所有函数必须声明返回类型 | `function getUser(): User` |
| ✅ **API 类型定义** | 所有 API 必须定义类型 | `axios.get<ApiResponse<User>>('/api')` |
| ✅ **Schema 驱动** | 类型从 Schema 推导 | `type User = z.infer<typeof UserSchema>` |
### 2. 逻辑集中化
| 层级 | 职责 | 禁止行为 |
|------|------|----------|
| **Controller** | 请求/响应 + 权限校验 | ❌ 业务逻辑 |
| **Service** | 业务逻辑 + 状态流转 | ✅ 核心逻辑 |
| **Repository** | 数据库 CRUD | ❌ 业务逻辑 |
### 3. 数据安全
| 约束 | 说明 |
|------|------|
| **表前缀** | 所有表必须以 `cf_` 开头 |
| **金额字段** | 必须使用 `decimal(10,2)` |
| **五元组** | tenantId, shopId, taskId, traceId, businessType |
### 4. 业务红线
| 场景 | 规则 |
|------|------|
| **B2B 利润率** | < 15% → 禁止报价 |
| **B2C 利润率** | < 20% → 触发风控预警 |
| **决策流程** | SUGGESTED → PENDING_REVIEW → EXECUTED/REJECTED |
---
## 🟡 开发流程
### 标准开发顺序
```
1. Service业务逻辑
2. Repository数据访问
3. Controller接口层
4. Frontend前端实现
5. Test测试用例
```
### 类型转换流程
```
API 返回数据
Schema 验证zod
DTO 转换
Domain 模型
```
---
## 🟢 代码模板
### Service 层模板
```typescript
import { z } from 'zod'
import { User, UserDTO } from '@/types'
import { UserSchema } from '@/types/domain/User.schema'
export class UserService {
constructor(
private readonly userRepository: UserRepository
) {}
/**
* 创建用户
* [BE-U001] 用户创建服务
*/
async createUser(request: CreateUserRequest): Promise<UserDTO> {
// 1. 验证请求数据
const validatedRequest = CreateUserRequestSchema.parse(request)
// 2. 创建领域模型
const user = UserSchema.parse({
id: crypto.randomUUID(),
username: validatedRequest.username,
email: validatedRequest.email,
role: validatedRequest.role,
status: 'ACTIVE',
createdAt: new Date(),
updatedAt: new Date()
})
// 3. 保存到数据库
const savedUser = await this.userRepository.create(user)
// 4. 转换为 DTO
return toUserDTO(savedUser)
}
}
```
### Controller 层模板
```typescript
import { Request, Response } from 'express'
import { CreateUserRequest, CreateUserResponse } from '@/types'
import { createSuccessResponse, createErrorResponse } from '@/types/shared/Response'
export class UserController {
constructor(private readonly userService: UserService) {}
async createUser(req: Request, res: Response): Promise<void> {
try {
const request: CreateUserRequest = CreateUserRequestSchema.parse(req.body)
const userDTO = await this.userService.createUser(request)
const response = createSuccessResponse({
id: userDTO.id,
username: userDTO.username,
email: userDTO.email,
role: userDTO.role,
createdAt: userDTO.createdAt
})
res.json(response)
} catch (error) {
const response = createErrorResponse(
'INTERNAL_ERROR',
error instanceof Error ? error.message : 'Unknown error'
)
res.status(500).json(response)
}
}
}
```
### Schema 定义模板
```typescript
import { z } from 'zod'
export const UserSchema = z.object({
id: z.string().uuid(),
username: z.string().min(3).max(50),
email: z.string().email(),
role: z.enum(['ADMIN', 'MANAGER', 'OPERATOR']),
status: z.enum(['ACTIVE', 'INACTIVE']).default('ACTIVE'),
createdAt: z.date(),
updatedAt: z.date()
})
export type User = z.infer<typeof UserSchema>
```
---
## 🔵 常见错误对比
### ❌ 错误示例 vs ✅ 正确示例
#### 1. 类型定义
```typescript
// ❌ 错误:使用 any
function handle(data: any) {
return data.name
}
// ✅ 正确:使用 unknown + 类型守卫
function handle(data: unknown) {
if (typeof data === 'object' && data !== null && 'name' in data) {
return (data as { name: string }).name
}
throw new Error('Invalid data')
}
```
#### 2. 函数返回类型
```typescript
// ❌ 错误:未声明返回类型
function getUser(userId: string) {
return userRepository.findById(userId)
}
// ✅ 正确:声明返回类型
function getUser(userId: string): Promise<User | null> {
return userRepository.findById(userId)
}
```
#### 3. API 调用
```typescript
// ❌ 错误:未定义类型
const response = await axios.get('/api/users')
// ✅ 正确:定义类型
const response = await axios.get<ApiResponse<User[]>>('/api/users')
const users = response.data.data
```
#### 4. 业务逻辑位置
```typescript
// ❌ 错误Controller 中写业务逻辑
async createUser(req: Request, res: Response) {
const { username, email } = req.body
if (!username || !email) {
return res.status(400).json({ error: 'Missing fields' })
}
const user = await this.userRepository.create({ username, email })
res.json(user)
}
// ✅ 正确Controller 只负责请求/响应
async createUser(req: Request, res: Response) {
try {
const userDTO = await this.userService.createUser(req.body)
res.json(createSuccessResponse(userDTO))
} catch (error) {
res.status(500).json(createErrorResponse('ERROR', error.message))
}
}
```
#### 5. 类型定义方式
```typescript
// ❌ 错误:手动定义类型
interface User {
id: string
name: string
email: string
}
// ✅ 正确:从 Schema 推导类型
const UserSchema = z.object({
id: z.string().uuid(),
name: z.string(),
email: z.string().email()
})
type User = z.infer<typeof UserSchema>
```
---
## 🟣 检查清单
### 开发前检查
- [ ] 已阅读相关业务文档
- [ ] 已理解状态机流转
- [ ] 已确认任务依赖关系
- [ ] 已声明文件占用
### 开发中检查
- [ ] 所有函数已声明返回类型
- [ ] 所有 API 调用已定义类型
- [ ] 业务逻辑在 Service 层
- [ ] 类型从 Schema 推导
- [ ] 所有类型从 `/types` 导入
### 提交前检查
- [ ] `tsc --noEmit` 无错误
- [ ] `eslint` 无错误
- [ ] 单元测试通过
- [ ] 五元组已填写
- [ ] JSDoc 注释完整
---
## 🟤 快速导航
| 文档 | 路径 |
|------|------|
| **TypeScript 编译规约** | `docs/01_Architecture/13_TypeScript_Standards.md` |
| **代码质量规范** | `docs/01_Architecture/14_Code_Quality_Standards.md` |
| **Schema 驱动开发** | `docs/01_Architecture/15_Schema_Driven_Development.md` |
| **统一类型管理** | `docs/01_Architecture/16_Unified_Type_Management.md` |
| **AI 开发规则** | `docs/05_AI/02_Rules.md` |
| **项目硬性约束** | `.trae/rules/project-specific-rules.md` |
---
## 🟠 紧急情况处理
### 编译错误
```bash
# 1. 检查类型错误
npm run typecheck
# 2. 修复 ESLint 错误
npm run lint:fix
# 3. 重新编译
npm run build
```
### 类型错误
```typescript
// 快速修复:使用类型守卫
if (isUser(data)) {
// TypeScript 知道 data 是 User 类型
}
// 快速修复:使用 Schema 验证
const user = UserSchema.parse(data)
```
### 业务逻辑错误
```typescript
// 检查:业务逻辑是否在 Service 层
// 检查:状态流转是否遵循状态机
// 检查:权限校验是否完整
```
---
*本卡片仅供快速参考,详细规范请查阅完整文档。*

View File

@@ -0,0 +1,359 @@
# AI 开发检查清单AI Development Checklist
> **模块**: 05_AI - AI 开发检查清单
> **更新日期**: 2026-03-20
> **用途**: AI 开发各阶段的强制检查项
---
## 📋 使用说明
AI 在开发过程中必须在以下阶段执行检查清单:
1. **开发前** - 任务领取和规划阶段
2. **开发中** - 编码实现阶段
3. **提交前** - 代码提交前验证
4. **交付后** - 任务完成确认
---
## 🔵 开发前检查清单Pre-Development Checklist
### 1. 任务理解
- [ ] **已阅读任务文档**
- 任务 ID 和描述
- 验收标准
- 依赖关系
- [ ] **已理解业务逻辑**
- 业务闭环流程
- 状态机流转
- 权限要求
- [ ] **已确认技术方案**
- 技术栈选择
- 架构设计
- 接口定义
### 2. 文档查阅
- [ ] **已查阅相关文档**
- [ ] `.trae/rules/project-specific-rules.md` - 硬性约束
- [ ] `docs/05_AI/02_Rules.md` - AI 开发规则
- [ ] `docs/05_AI/04_Quick_Reference_Card.md` - 快速参考
- [ ] `docs/01_Architecture/13_TypeScript_Standards.md` - TypeScript 规范
- [ ] `docs/01_Architecture/15_Schema_Driven_Development.md` - Schema 驱动
- [ ] **已理解领域模型**
- 实体关系
- 数据模型
- 业务规则
### 3. 任务领取
- [ ] **已检查任务状态**
- 任务状态为 `pending`
- 无其他 Agent 占用
- [ ] **已声明占用**
- 在 Task_Overview.md 声明占用
- 声明涉及文件
- 声明预计完成时间
- [ ] **已领取完整任务包**
- 领取同一闭环的完整任务链
- 最小粒度不少于 2 个相关任务
---
## 🟢 开发中检查清单During Development Checklist
### 1. TypeScript 类型安全
- [ ] **类型定义**
- [ ] 所有函数已声明返回类型
- [ ] 所有变量已声明类型
- [ ] 所有参数已声明类型
- [ ] 禁止使用 `any` 类型
- [ ] **Schema 驱动**
- [ ] 类型从 Schemazod推导
- [ ] 所有外部数据经过 Schema 验证
- [ ] 类型守卫已实现
- [ ] **类型导入**
- [ ] 所有类型从 `/types` 目录导入
- [ ] 禁止各模块重复定义类型
### 2. 逻辑集中化
- [ ] **Service 层**
- [ ] 所有业务逻辑在 Service 层
- [ ] 状态流转在 Service 层
- [ ] 多模块协同在 Service 层
- [ ] **Controller 层**
- [ ] 只负责请求/响应
- [ ] 只负责权限校验
- [ ] 无业务逻辑
- [ ] **Repository 层**
- [ ] 只负责数据库 CRUD
- [ ] 无业务逻辑
### 3. 数据安全
- [ ] **数据库**
- [ ] 表名以 `cf_` 开头
- [ ] 金额字段使用 `decimal(10,2)`
- [ ] 复杂查询通过 `EXPLAIN` 校验
- [ ] **五元组**
- [ ] tenantId 已填写
- [ ] shopId 已填写
- [ ] taskId 已填写
- [ ] traceId 已填写
- [ ] businessType 已填写
### 4. 业务规则
- [ ] **状态机**
- [ ] 状态流转遵循 STATE_MACHINE
- [ ] 非法状态流转已拦截
- [ ] **权限校验**
- [ ] 使用 `authorize()` 中间件
- [ ] 数据隔离已实现
- [ ] **利润红线**
- [ ] B2B 利润率 ≥ 15%
- [ ] B2C 利润率 ≥ 20%
### 5. 代码质量
- [ ] **命名规范**
- [ ] 服务类使用 `Service` 后缀
- [ ] 控制器类使用 `Controller` 后缀
- [ ] 仓库类使用 `Repository` 后缀
- [ ] **注释规范**
- [ ] 每个服务类包含完整 JSDoc
- [ ] 每个方法包含参数和返回值说明
- [ ] 关键业务逻辑已添加注释
- [ ] 任务 ID 已标注
- [ ] **文件规模**
- [ ] 单文件 ≤ 1500 行
- [ ] 单函数 ≤ 120 行
- [ ] UI 组件 ≤ 300 行
---
## 🟡 提交前检查清单Pre-Commit Checklist
### 1. 编译检查
- [ ] **TypeScript 编译**
```bash
npm run typecheck
```
- [ ] 无类型错误
- [ ] 无编译警告
- [ ] **ESLint 检查**
```bash
npm run lint
```
- [ ] 无 ESLint 错误
- [ ] 已修复可自动修复的问题
### 2. 测试检查
- [ ] **单元测试**
```bash
npm run test
```
- [ ] 所有测试通过
- [ ] 测试覆盖率达标
- [ ] **集成测试**
- [ ] 核心流程测试通过
- [ ] 异常流程测试通过
### 3. 代码审查
- [ ] **自我审查**
- [ ] 业务逻辑正确性
- [ ] 状态机遵循情况
- [ ] 权限校验完整性
- [ ] 错误处理完整性
- [ ] 性能优化
- [ ] 安全漏洞
- [ ] **类型安全审查**
- [ ] 无 `any` 类型
- [ ] 所有函数有返回类型
- [ ] 所有 API 有类型定义
- [ ] 类型从 Schema 推导
### 4. 文档同步
- [ ] **文档更新**
- [ ] API 文档已更新
- [ ] 数据库文档已更新
- [ ] 任务状态已更新
---
## 🟠 交付后检查清单Post-Delivery Checklist
### 1. 任务完成确认
- [ ] **功能验证**
- [ ] 功能测试通过
- [ ] 符合验收标准
- [ ] 无回归问题
- [ ] **文档同步**
- [ ] 任务状态更新为 `completed`
- [ ] 相关文档已更新
- [ ] 注释和 JSDoc 完整
### 2. 资源释放
- [ ] **占用释放**
- [ ] Task_Overview.md 占用声明已清除
- [ ] 文件占用已释放
- [ ] **知识沉淀**
- [ ] 遇到的问题已记录
- [ ] 解决方案已文档化
### 3. 质量确认
- [ ] **代码质量**
- [ ] `GetDiagnostics` 无错误
- [ ] 代码审查通过
- [ ] 测试覆盖率达标
- [ ] **部署标准**
- [ ] 数据库表已初始化
- [ ] 核心逻辑已闭环
- [ ] 最小冒烟测试已补充
---
## 🔴 禁止行为清单Forbidden Actions
### TypeScript 相关
- ❌ 使用 `any` 类型
- ❌ 函数不声明返回类型
- ❌ API 调用不定义类型
- ❌ 手动定义类型(不从 Schema 推导)
- ❌ 各模块重复定义类型
### 架构相关
- ❌ Controller 中写业务逻辑
- ❌ 前端直接写业务规则
- ❌ 直接操作数据库(不通过 Repository
- ❌ 跨 Domain 直接操作数据库模型
- ❌ 跳过权限校验
### 数据相关
- ❌ 表名不以 `cf_` 开头
- ❌ 金额字段使用 float/double
- ❌ 代码中执行 `DROP/TRUNCATE`
- ❌ 五元组未填写
### 业务相关
- ❌ Agent 直接修改核心业务数据
- ❌ B2B 利润率 < 15% 报价
- ❌ B2C 利润率 < 20% 无预警
- ❌ 非法状态流转
### 协作相关
- ❌ 单独领取任务包内的部分任务
- ❌ 不声明占用直接开始开发
- ❌ 跨模块同时占用多个任务包
- ❌ 占用超过 24 小时未释放
---
## 🟣 快速检查命令
```bash
# TypeScript 类型检查
npm run typecheck
# ESLint 检查
npm run lint
# ESLint 自动修复
npm run lint:fix
# 单元测试
npm run test
# 测试覆盖率
npm run test:coverage
# 完整验证
npm run validate
# 构建
npm run build
```
---
## 📊 检查清单执行记录
AI 在每个阶段完成后,应记录检查清单执行情况:
```markdown
## 检查清单执行记录
**任务 ID**: BE-U001
**Agent**: AI-Backend-1
**开始时间**: 2026-03-20 10:00
### 开发前检查
- [x] 已阅读任务文档
- [x] 已理解业务逻辑
- [x] 已声明占用
- 执行时间: 2026-03-20 10:05
### 开发中检查
- [x] TypeScript 类型安全
- [x] 逻辑集中化
- [x] 数据安全
- [x] 业务规则
- [x] 代码质量
- 执行时间: 2026-03-20 12:00
### 提交前检查
- [x] TypeScript 编译
- [x] ESLint 检查
- [x] 单元测试
- [x] 代码审查
- 执行时间: 2026-03-20 13:00
### 交付后检查
- [x] 功能验证
- [x] 文档同步
- [x] 资源释放
- 执行时间: 2026-03-20 14:00
**完成时间**: 2026-03-20 14:00
**状态**: ✅ 完成
```
---
*本检查清单为强制执行项AI 必须在每个阶段完成所有检查。*

View File

@@ -0,0 +1,962 @@
# 错误示例与正确示例对比Wrong vs Right Examples
> **模块**: 05_AI - 错误示例与正确示例对比
> **更新日期**: 2026-03-20
> **用途**: 帮助 AI 快速识别错误代码模式并避免重复犯错
---
## 📋 使用说明
本文档通过对比错误示例和正确示例,帮助 AI
1. **快速识别错误模式**
2. **理解正确实现方式**
3. **避免重复犯错**
4. **提高代码质量**
---
## 1⃣ TypeScript 类型安全
### 1.1 禁止 any 类型
#### ❌ 错误示例
```typescript
// 错误:使用 any 类型
function handleData(data: any) {
return data.name
}
function processUser(user: any) {
console.log(user.email)
return user.id
}
const userData: any = fetchUser()
```
#### ✅ 正确示例
```typescript
// 正确:使用 unknown + 类型守卫
function handleData(data: unknown) {
if (typeof data === 'object' && data !== null && 'name' in data) {
return (data as { name: string }).name
}
throw new Error('Invalid data')
}
// 正确:使用类型守卫函数
function isUser(data: unknown): data is User {
return (
typeof data === 'object' &&
data !== null &&
'id' in data &&
'email' in data &&
typeof (data as User).id === 'string' &&
typeof (data as User).email === 'string'
)
}
function processUser(data: unknown) {
if (isUser(data)) {
console.log(data.email)
return data.id
}
throw new Error('Invalid user data')
}
// 正确:使用 Schema 验证
const userData = UserSchema.parse(fetchUser())
```
---
### 1.2 函数必须声明返回类型
#### ❌ 错误示例
```typescript
// 错误:未声明返回类型
function getUser(userId: string) {
return userRepository.findById(userId)
}
function calculateTotal(items: Item[]) {
return items.reduce((sum, item) => sum + item.price, 0)
}
async function fetchData(url: string) {
const response = await fetch(url)
return response.json()
}
```
#### ✅ 正确示例
```typescript
// 正确:声明返回类型
function getUser(userId: string): Promise<User | null> {
return userRepository.findById(userId)
}
function calculateTotal(items: Item[]): number {
return items.reduce((sum, item) => sum + item.price, 0)
}
async function fetchData<T>(url: string): Promise<T> {
const response = await fetch(url)
return response.json() as Promise<T>
}
```
---
### 1.3 API 必须定义类型
#### ❌ 错误示例
```typescript
// 错误:未定义类型
const response = await axios.get('/api/users')
const users = response.data
const createResponse = await axios.post('/api/users', userData)
const product = await fetch('/api/products/123').then(res => res.json())
```
#### ✅ 正确示例
```typescript
// 正确:定义请求和响应类型
interface ApiResponse<T> {
success: boolean
data: T
message?: string
}
interface User {
id: string
name: string
email: string
}
const response = await axios.get<ApiResponse<User[]>>('/api/users')
const users = response.data.data
const createResponse = await axios.post<ApiResponse<User>>('/api/users', userData)
const product = await fetch('/api/products/123')
.then(res => res.json() as Promise<ApiResponse<Product>>)
.then(data => data.data)
```
---
### 1.4 类型从 Schema 推导
#### ❌ 错误示例
```typescript
// 错误:手动定义类型
interface User {
id: string
name: string
email: string
age: number
}
interface Product {
id: string
name: string
price: number
}
// 错误:类型和 Schema 不一致
const UserSchema = z.object({
id: z.string(),
name: z.string(),
email: z.string().email()
// 缺少 age 字段
})
type User = z.infer<typeof UserSchema>
```
#### ✅ 正确示例
```typescript
// 正确:从 Schema 推导类型
import { z } from 'zod'
const UserSchema = z.object({
id: z.string().uuid(),
name: z.string().min(1).max(100),
email: z.string().email(),
age: z.number().int().positive()
})
type User = z.infer<typeof UserSchema>
const ProductSchema = z.object({
id: z.string().uuid(),
name: z.string().min(1).max(200),
price: z.number().positive()
})
type Product = z.infer<typeof ProductSchema>
```
---
### 1.5 统一类型中心
#### ❌ 错误示例
```typescript
// 错误:各模块重复定义类型
// dashboard/src/pages/User/User.tsx
interface User {
id: string
name: string
}
// server/src/models/User.ts
interface User {
id: string
name: string
email: string
}
// extension/src/types/User.ts
interface User {
id: string
name: string
email: string
role: string
}
```
#### ✅ 正确示例
```typescript
// 正确:从类型中心导入
// types/domain/User.ts
export const UserSchema = z.object({
id: z.string().uuid(),
name: z.string(),
email: z.string().email(),
role: z.enum(['ADMIN', 'MANAGER', 'OPERATOR'])
})
export type User = z.infer<typeof UserSchema>
// dashboard/src/pages/User/User.tsx
import { User } from '@/types/domain/User'
// server/src/models/User.ts
import { User } from '@/types/domain/User'
// extension/src/types/User.ts
import { User } from '@/types/domain/User'
```
---
## 2⃣ 逻辑集中化
### 2.1 Controller 层职责
#### ❌ 错误示例
```typescript
// 错误Controller 中写业务逻辑
export class UserController {
async createUser(req: Request, res: Response) {
const { username, email, password } = req.body
// 业务逻辑在 Controller 中
if (!username || !email || !password) {
return res.status(400).json({ error: 'Missing fields' })
}
if (password.length < 8) {
return res.status(400).json({ error: 'Password too short' })
}
const hashedPassword = await bcrypt.hash(password, 10)
const user = await this.userRepository.create({
username,
email,
passwordHash: hashedPassword,
role: 'OPERATOR',
status: 'ACTIVE'
})
res.json(user)
}
}
```
#### ✅ 正确示例
```typescript
// 正确Controller 只负责请求/响应
export class UserController {
constructor(private readonly userService: UserService) {}
async createUser(req: Request, res: Response) {
try {
const userDTO = await this.userService.createUser(req.body)
res.json(createSuccessResponse(userDTO))
} catch (error) {
if (error instanceof ValidationError) {
res.status(400).json(createErrorResponse('VALIDATION_ERROR', error.message))
} else {
res.status(500).json(createErrorResponse('INTERNAL_ERROR', error.message))
}
}
}
}
// 业务逻辑在 Service 层
export class UserService {
async createUser(request: CreateUserRequest): Promise<UserDTO> {
// 1. 验证请求数据
const validatedRequest = CreateUserRequestSchema.parse(request)
// 2. 业务逻辑处理
const hashedPassword = await this.hashPassword(validatedRequest.password)
// 3. 创建领域模型
const user = UserSchema.parse({
id: crypto.randomUUID(),
username: validatedRequest.username,
email: validatedRequest.email,
passwordHash: hashedPassword,
role: validatedRequest.role || 'OPERATOR',
status: 'ACTIVE',
createdAt: new Date(),
updatedAt: new Date()
})
// 4. 保存到数据库
const savedUser = await this.userRepository.create(user)
// 5. 转换为 DTO
return toUserDTO(savedUser)
}
}
```
---
### 2.2 前端业务规则
#### ❌ 错误示例
```typescript
// 错误:前端直接写业务规则
function ProductCard({ product }: { product: Product }) {
// 业务规则在前端
const profitMargin = (product.price - product.cost) / product.price
// 业务判断在前端
const canSell = profitMargin >= 0.15
// 状态判断在前端
const statusText = product.status === 'ACTIVE' ? '可售' : '不可售'
return (
<div>
<h3>{product.name}</h3>
<p>: {(profitMargin * 100).toFixed(2)}%</p>
<p>: {statusText}</p>
{canSell && <button></button>}
</div>
)
}
```
#### ✅ 正确示例
```typescript
// 正确:前端只负责展示
function ProductCard({ product }: { product: ProductDTO }) {
return (
<div>
<h3>{product.name}</h3>
<p>: {product.profitMargin}%</p>
<p>: {product.statusText}</p>
{product.canSell && <button onClick={() => handleBuy(product)}></button>}
</div>
)
}
// 业务规则在 Service 层
export class ProductService {
async getProduct(id: string): Promise<ProductDTO> {
const product = await this.productRepository.findById(id)
if (!product) {
throw new NotFoundError('Product', id)
}
// 业务规则计算
const profitMargin = this.calculateProfitMargin(product)
const canSell = this.checkProfitMargin(profitMargin, product.businessType)
const statusText = this.getStatusText(product.status)
return {
...product,
profitMargin: (profitMargin * 100).toFixed(2),
canSell,
statusText
}
}
private calculateProfitMargin(product: Product): number {
return (product.price - product.cost) / product.price
}
private checkProfitMargin(margin: number, businessType: 'B2B' | 'B2C'): boolean {
const threshold = businessType === 'B2B' ? 0.15 : 0.20
return margin >= threshold
}
}
```
---
### 2.3 数据库操作
#### ❌ 错误示例
```typescript
// 错误:直接操作数据库
export class UserController {
async getUser(req: Request, res: Response) {
// 直接使用数据库连接
const user = await db('users').where({ id: req.params.id }).first()
res.json(user)
}
}
// 错误:跨模块直接操作数据库
export class OrderService {
async createOrder(orderData: OrderData) {
// 直接操作商品表
const product = await db('products').where({ id: orderData.productId }).first()
// 直接更新库存
await db('inventory').where({ product_id: orderData.productId }).decrement('quantity', orderData.quantity)
// 直接创建订单
const order = await db('orders').insert(orderData)
return order
}
}
```
#### ✅ 正确示例
```typescript
// 正确:通过 Repository 层操作数据库
export class UserController {
constructor(
private readonly userService: UserService
) {}
async getUser(req: Request, res: Response) {
const user = await this.userService.getUser(req.params.id)
res.json(createSuccessResponse(user))
}
}
// 正确:通过 Service 层协调多模块
export class OrderService {
constructor(
private readonly orderRepository: OrderRepository,
private readonly productService: ProductService,
private readonly inventoryService: InventoryService
) {}
async createOrder(orderData: OrderData): Promise<Order> {
// 通过 Service 获取商品信息
const product = await this.productService.getProduct(orderData.productId)
// 通过 Service 更新库存
await this.inventoryService.decreaseStock(orderData.productId, orderData.quantity)
// 通过 Repository 创建订单
const order = await this.orderRepository.create(orderData)
return order
}
}
```
---
## 3⃣ 数据安全
### 3.1 表命名规范
#### ❌ 错误示例
```typescript
// 错误:表名不以 cf_ 开头
await db.schema.createTable('users', (table) => {
table.string('id').primary()
table.string('name')
table.string('email')
})
await db.schema.createTable('products', (table) => {
table.string('id').primary()
table.string('name')
table.decimal('price')
})
```
#### ✅ 正确示例
```typescript
// 正确:表名以 cf_ 开头
await db.schema.createTable('cf_users', (table) => {
table.string('id').primary()
table.string('name')
table.string('email')
})
await db.schema.createTable('cf_products', (table) => {
table.string('id').primary()
table.string('name')
table.decimal('price', 10, 2) // 金额字段使用 decimal(10,2)
})
```
---
### 3.2 金额字段
#### ❌ 错误示例
```typescript
// 错误:金额字段使用 float/double
await db.schema.createTable('cf_orders', (table) => {
table.string('id').primary()
table.float('total_amount') // 错误
table.double('subtotal') // 错误
})
// 错误:金额计算使用浮点数
const total = 10.5 + 20.3 // 30.800000000000004
const price = product.price * 1.1 // 浮点数精度问题
```
#### ✅ 正确示例
```typescript
// 正确:金额字段使用 decimal(10,2)
await db.schema.createTable('cf_orders', (table) => {
table.string('id').primary()
table.decimal('total_amount', 10, 2) // 正确
table.decimal('subtotal', 10, 2) // 正确
})
// 正确:金额计算使用整数(分)或 decimal
const total = Math.round((10.5 + 20.3) * 100) / 100 // 30.80
const price = Math.round(product.price * 1.1 * 100) / 100
// 或使用 decimal.js
import Decimal from 'decimal.js'
const total = new Decimal(10.5).plus(20.3).toNumber() // 30.8
```
---
### 3.3 五元组
#### ❌ 错误示例
```typescript
// 错误:缺少五元组
async function processOrder(orderId: string) {
const order = await orderRepository.findById(orderId)
await orderService.process(order)
}
// 错误:五元组不完整
const log = {
orderId: '123',
action: 'process',
timestamp: new Date()
}
```
#### ✅ 正确示例
```typescript
// 正确:包含完整五元组
interface TaskContext {
tenantId: string
shopId: string
taskId: string
traceId: string
businessType: 'TOC' | 'TOB'
}
async function processOrder(orderId: string, context: TaskContext) {
const order = await orderRepository.findById(orderId)
// 记录日志时包含五元组
logger.info('Processing order', {
...context,
orderId,
action: 'process'
})
await orderService.process(order, context)
}
// 正确:五元组完整
const log = {
tenantId: 'tenant-123',
shopId: 'shop-456',
taskId: 'task-789',
traceId: 'trace-abc',
businessType: 'TOC',
orderId: '123',
action: 'process',
timestamp: new Date()
}
```
---
## 4⃣ 业务规则
### 4.1 状态机流转
#### ❌ 错误示例
```typescript
// 错误:非法状态流转
async function updateOrderStatus(orderId: string, newStatus: string) {
const order = await orderRepository.findById(orderId)
// 直接修改状态,未检查流转规则
order.status = newStatus
await orderRepository.update(orderId, order)
}
// 错误:跳过状态
async function shipOrder(orderId: string) {
const order = await orderRepository.findById(orderId)
// 从 PENDING 直接跳到 SHIPPED跳过 PAID 和 PROCESSING
order.status = 'SHIPPED'
await orderRepository.update(orderId, order)
}
```
#### ✅ 正确示例
```typescript
// 正确:通过 Service 层遵循状态机
export class OrderService {
private readonly STATE_TRANSITIONS = {
PENDING: ['PAID', 'CANCELLED'],
PAID: ['PROCESSING', 'REFUNDED'],
PROCESSING: ['SHIPPED', 'REFUNDED'],
SHIPPED: ['COMPLETED', 'REFUNDED'],
COMPLETED: [],
CANCELLED: [],
REFUNDED: []
}
async updateOrderStatus(
orderId: string,
newStatus: OrderStatus,
context: TaskContext
): Promise<Order> {
const order = await this.orderRepository.findById(orderId)
if (!order) {
throw new NotFoundError('Order', orderId)
}
// 检查状态流转是否合法
if (!this.isValidTransition(order.status, newStatus)) {
throw new Error(`Invalid state transition: ${order.status} -> ${newStatus}`)
}
// 更新状态
order.status = newStatus
order.updatedAt = new Date()
const updatedOrder = await this.orderRepository.update(orderId, order)
// 记录状态变更日志
logger.info('Order status updated', {
...context,
orderId,
fromStatus: order.status,
toStatus: newStatus
})
return updatedOrder
}
private isValidTransition(from: OrderStatus, to: OrderStatus): boolean {
return this.STATE_TRANSITIONS[from]?.includes(to) || false
}
}
```
---
### 4.2 权限校验
#### ❌ 错误示例
```typescript
// 错误:硬编码权限判断
async function deleteUser(userId: string, req: Request) {
const user = req.user
// 硬编码权限判断
if (user.role !== 'ADMIN') {
throw new Error('Permission denied')
}
await userRepository.delete(userId)
}
// 错误:跳过权限校验
async function getAllUsers() {
return await userRepository.findAll()
}
```
#### ✅ 正确示例
```typescript
// 正确:使用 authorize 中间件
import { authorize } from '@/middleware/auth'
router.delete('/users/:id',
authorize('user:delete'),
userController.deleteUser
)
// 正确Controller 中调用 Service
export class UserController {
async deleteUser(req: Request, res: Response) {
await this.userService.deleteUser(req.params.id)
res.json(createSuccessResponse({ message: 'User deleted' }))
}
}
// 正确Service 层实现权限逻辑
export class UserService {
async deleteUser(userId: string): Promise<void> {
// 检查用户是否存在
const user = await this.userRepository.findById(userId)
if (!user) {
throw new NotFoundError('User', userId)
}
// 执行删除
await this.userRepository.delete(userId)
}
}
```
---
### 4.3 利润红线
#### ❌ 错误示例
```typescript
// 错误:未检查利润红线
async function createQuote(productId: string, price: number) {
const product = await productRepository.findById(productId)
// 未检查利润率
const quote = await quoteRepository.create({
productId,
price,
status: 'ACTIVE'
})
return quote
}
// 错误:仅用售价 - 采购价判断
const profit = price - product.cost
if (profit > 0) {
// 允许报价
}
```
#### ✅ 正确示例
```typescript
// 正确:使用 PricingService 检查利润红线
export class QuoteService {
constructor(
private readonly pricingService: PricingService,
private readonly quoteRepository: QuoteRepository
) {}
async createQuote(
productId: string,
price: number,
businessType: 'B2B' | 'B2C'
): Promise<Quote> {
const product = await this.productRepository.findById(productId)
if (!product) {
throw new NotFoundError('Product', productId)
}
// 计算净利率(含平台费/物流/税费/汇率/售后/广告摊销)
const profitMargin = await this.pricingService.calculateProfitMargin({
price,
cost: product.cost,
platform: product.platform,
businessType
})
// 检查利润红线
if (businessType === 'B2B' && profitMargin < 0.15) {
throw new Error('B2B profit margin must be at least 15%')
}
if (businessType === 'B2C' && profitMargin < 0.20) {
// 触发风控预警
await this.riskAlertService.createAlert({
type: 'LOW_PROFIT_MARGIN',
productId,
profitMargin,
threshold: 0.20
})
}
// 创建报价
const quote = await this.quoteRepository.create({
productId,
price,
profitMargin,
status: 'ACTIVE'
})
return quote
}
}
```
---
## 5⃣ Mock 数据
### 5.1 硬编码 Mock 数据
#### ❌ 错误示例
```typescript
// 错误:在业务组件中硬编码 Mock 数据
function ProductList() {
const products = [
{ id: 1, name: 'Mock商品1', price: 100 },
{ id: 2, name: 'Mock商品2', price: 200 }
]
return (
<div>
{products.map(p => (
<div key={p.id}>{p.name}</div>
))}
</div>
)
}
// 错误:通过 if 判断切换 Mock/真实数据
async function getProducts() {
if (process.env.NODE_ENV === 'development') {
return mockProducts
}
return await api.getProducts()
}
```
#### ✅ 正确示例
```typescript
// 正确:通过 DataSource 抽象层
// services/productDataSource.ts
import { ProductDTOSchema, type ProductDTO } from '@/types'
export const productDataSource = {
async list(): Promise<ProductDTO[]> {
if (process.env.REACT_APP_USE_MOCK === 'true') {
const { mockProducts } = await import('@/mock/data/product.mock')
return mockProducts.map(p => ProductDTOSchema.parse(p))
}
const response = await api.getProducts()
return response.data.map(p => ProductDTOSchema.parse(p))
}
}
// components/ProductList.tsx
function ProductList() {
const { data: products } = useQuery({
queryKey: ['products'],
queryFn: () => productDataSource.list()
})
return (
<div>
{products?.map(p => (
<div key={p.id}>{p.name}</div>
))}
</div>
)
}
// mock/data/product.mock.ts
/**
* [MOCK] 商品 Mock 数据
* AI注意: 这是Mock实现不是真实业务逻辑
* 仅在USE_MOCK=true时启用
*/
export const mockProducts = [
{ id: '1', name: '商品1', price: 100 },
{ id: '2', name: '商品2', price: 200 }
]
```
---
## 📊 总结
| 类别 | 常见错误 | 正确做法 |
|------|----------|----------|
| **TypeScript** | 使用 any、不声明返回类型 | 使用 unknown + 类型守卫、声明返回类型 |
| **逻辑集中化** | Controller 写业务逻辑 | 业务逻辑在 Service 层 |
| **数据安全** | 表名无前缀、金额用 float | 表名 cf_ 前缀、金额用 decimal(10,2) |
| **业务规则** | 非法状态流转、跳过权限校验 | 遵循状态机、使用 authorize 中间件 |
| **Mock 数据** | 硬编码 Mock、if 判断切换 | DataSource 抽象层、环境变量控制 |
---
*本文档持续更新,帮助 AI 避免常见错误。*

View File

@@ -0,0 +1,360 @@
# TypeScript 编译错误修复方案TypeScript Error Fix Guide
> **模块**: 05_AI - TypeScript 编译错误修复方案
> **更新日期**: 2026-03-20
> **用途**: 解决 613 个 TypeScript 编译错误的完整方案
---
## 📊 错误现状
### 当前错误统计
```bash
$ npx tsc --noEmit 2>&1 | Select-String -Pattern "^src/" | Measure-Object
Count: 613
```
### 错误分布分析
| 错误类型 | 预估占比 | 严重程度 |
|---------|---------|---------|
| **类型不匹配** | 40% | 🔴 高 |
| **类型丢失any** | 25% | 🔴 高 |
| **模块导入/导出错误** | 15% | 🟡 中 |
| **未处理的 undefined/null** | 10% | 🟡 中 |
| **编译器配置问题** | 5% | 🟢 低 |
| **文件/路径问题** | 5% | 🟢 低 |
---
## 🎯 修复策略
### 策略一:分阶段修复(推荐)
#### 阶段 1修复编译器配置优先级🔴 最高)
**目标**:确保 tsconfig.json 配置正确
**步骤**
1. 检查 server/tsconfig.json 配置
2. 检查 dashboard/tsconfig.json 配置
3. 检查 extension/tsconfig.json 配置
4. 统一配置标准
**预期效果**:减少 5% 错误(约 30 个)
#### 阶段 2修复 any 类型(优先级:🔴 最高)
**目标**:消除所有 any 类型
**步骤**
1. 运行 `npx tsc --noEmit 2>&1 | Select-String "any"` 找到所有 any 相关错误
2. 逐个文件修复,使用 unknown + 类型守卫
3. 使用 ESLint 规则 `@typescript-eslint/no-explicit-any: error` 强制禁止
**预期效果**:减少 25% 错误(约 150 个)
#### 阶段 3修复类型不匹配优先级🔴 高)
**目标**:确保所有类型声明正确
**步骤**
1. 运行 `npx tsc --noEmit 2>&1 | Select-String "Type"` 找到类型不匹配错误
2. 检查函数参数和返回值类型
3. 检查对象属性类型
4. 使用 Schema 驱动类型定义
**预期效果**:减少 40% 错误(约 245 个)
#### 阶段 4修复模块导入错误优先级🟡 中)
**目标**:确保模块导入导出正确
**步骤**
1. 运行 `npx tsc --noEmit 2>&1 | Select-String "module"` 找到模块错误
2. 统一使用 ES 模块或 CommonJS
3. 检查路径别名配置
4. 修复循环依赖
**预期效果**:减少 15% 错误(约 92 个)
#### 阶段 5修复 undefined/null 问题(优先级:🟡 中)
**目标**:正确处理 undefined 和 null
**步骤**
1. 运行 `npx tsc --noEmit 2>&1 | Select-String "undefined\|null"` 找到相关错误
2. 使用可选链操作符 `?.`
3. 使用空值合并操作符 `??`
4. 添加类型守卫
**预期效果**:减少 10% 错误(约 61 个)
---
## 🔧 具体修复方案
### 1. 修复 any 类型
#### ❌ 错误示例
```typescript
function handleData(data: any) {
return data.name
}
const user: any = fetchUser()
```
#### ✅ 正确示例
```typescript
function handleData(data: unknown): string {
if (typeof data === 'object' && data !== null && 'name' in data) {
return String((data as { name: unknown }).name)
}
throw new Error('Invalid data')
}
const user: User = UserSchema.parse(fetchUser())
```
#### 批量修复脚本
```bash
# 查找所有 any 类型使用
grep -r ": any" server/src --include="*.ts" | wc -l
# 查找所有 any 类型使用PowerShell
Get-ChildItem -Path server\src -Filter *.ts -Recurse | Select-String ": any" | Measure-Object
```
---
### 2. 修复类型不匹配
#### ❌ 错误示例
```typescript
function getUser(id: string) {
return userRepository.findById(id) // 返回类型未声明
}
const price = res.price * 100 // res.price 类型未知
```
#### ✅ 正确示例
```typescript
function getUser(id: string): Promise<User | null> {
return userRepository.findById(id)
}
const price = Number(res.price) * 100 // 显式转换类型
```
#### 类型修复检查清单
- [ ] 所有函数声明返回类型
- [ ] 所有变量声明类型
- [ ] 所有参数声明类型
- [ ] 所有 API 调用定义类型
- [ ] 所有对象属性声明类型
---
### 3. 修复模块导入错误
#### ❌ 错误示例
```typescript
// 混用 ES 模块和 CommonJS
import { something } from './module'
const other = require('./other')
// 路径错误
import { User } from '../types/User' // 实际路径是 @/types/User
```
#### ✅ 正确示例
```typescript
// 统一使用 ES 模块
import { something } from './module'
import { other } from './other'
// 使用路径别名
import { User } from '@/types/User'
```
#### tsconfig.json 路径配置
```json
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"],
"@types/*": ["src/types/*"],
"@services/*": ["src/services/*"]
}
}
}
```
---
### 4. 修复 undefined/null 问题
#### ❌ 错误示例
```typescript
const name = user.name // user 可能为 null
const value = obj[key] // obj[key] 可能为 undefined
```
#### ✅ 正确示例
```typescript
const name = user?.name ?? 'Unknown'
const value = obj[key] ?? defaultValue
// 或使用类型守卫
if (user !== null && user !== undefined) {
const name = user.name
}
```
---
## 📝 ESLint 强制约束
### 安装依赖
```bash
npm install -D eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin
```
### .eslintrc.js 配置
```javascript
module.exports = {
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/recommended-requiring-type-checking'
],
parserOptions: {
project: './tsconfig.json'
},
rules: {
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/explicit-function-return-type': 'error',
'@typescript-eslint/explicit-module-boundary-types': 'error',
'@typescript-eslint/consistent-type-imports': 'error',
'@typescript-eslint/no-unused-vars': 'error',
'@typescript-eslint/no-non-null-assertion': 'warn',
'@typescript-eslint/prefer-nullish-coalescing': 'error',
'@typescript-eslint/prefer-optional-chain': 'error',
'@typescript-eslint/strict-boolean-expressions': 'error'
}
}
```
---
## 🚀 修复执行计划
### 第 1 周:配置与工具
| 任务 | 预计时间 | 负责人 |
|------|---------|--------|
| 检查并修复 tsconfig.json 配置 | 2h | AI |
| 安装并配置 ESLint | 2h | AI |
| 运行首次完整错误扫描 | 1h | AI |
| 分类错误并制定优先级 | 2h | AI |
### 第 2 周:核心错误修复
| 任务 | 预计时间 | 负责人 |
|------|---------|--------|
| 修复 any 类型错误(约 150 个) | 8h | AI |
| 修复类型不匹配错误(约 245 个) | 12h | AI |
| 修复模块导入错误(约 92 个) | 4h | AI |
### 第 3 周:剩余错误修复
| 任务 | 预计时间 | 负责人 |
|------|---------|--------|
| 修复 undefined/null 错误(约 61 个) | 4h | AI |
| 修复文件/路径错误(约 30 个) | 2h | AI |
| 全面测试验证 | 4h | AI |
---
## 📊 进度追踪
### 错误修复进度表
| 阶段 | 目标错误数 | 已修复 | 进度 |
|------|-----------|--------|------|
| 阶段 1配置修复 | 30 | 0 | 0% |
| 阶段 2any 类型 | 150 | 0 | 0% |
| 阶段 3类型不匹配 | 245 | 0 | 0% |
| 阶段 4模块导入 | 92 | 0 | 0% |
| 阶段 5undefined/null | 61 | 0 | 0% |
| **总计** | **613** | **0** | **0%** |
### 每日检查命令
```bash
# 检查剩余错误数
npx tsc --noEmit 2>&1 | Select-String -Pattern "^src/" | Measure-Object
# 检查 any 类型错误
npx tsc --noEmit 2>&1 | Select-String "any" | Measure-Object
# 检查类型错误
npx tsc --noEmit 2>&1 | Select-String "Type" | Measure-Object
# 检查模块错误
npx tsc --noEmit 2>&1 | Select-String "module" | Measure-Object
```
---
## ⚠️ 注意事项
### 修复原则
1. **优先修复配置问题**:配置错误会导致连锁反应
2. **批量修复相同类型错误**:提高效率
3. **每次修复后运行测试**:确保不引入新错误
4. **保持代码风格一致**:遵循项目规范
5. **记录修复过程**:便于后续参考
### 禁止行为
- ❌ 使用 `// @ts-ignore` 忽略错误
- ❌ 使用 `// @ts-nocheck` 禁用检查
- ❌ 将类型改为 `any` 来"解决"错误
- ❌ 不运行测试就提交修复
---
## 🔗 相关文档
- [TypeScript 编译规约](../01_Architecture/13_TypeScript_Standards.md)
- [代码质量规范](../01_Architecture/14_Code_Quality_Standards.md)
- [Schema 驱动开发](../01_Architecture/15_Schema_Driven_Development.md)
- [统一类型管理](../01_Architecture/16_Unified_Type_Management.md)
- [AI 开发检查清单](05_Development_Checklist.md)
- [错误示例对比](06_Wrong_vs_Right_Examples.md)
---
*本文档将随着错误修复进度持续更新。*

View File

@@ -0,0 +1,359 @@
# TypeScript 编译错误任务列表
> **创建日期**: 2026-03-20
> **总错误数**: 783 行输出(约 600+ 个错误)
> **状态**: 🔴 待领取
---
## 🔒 当前任务占用状态
| Agent | 任务ID | 涉及文件 | 开始时间 | 状态 |
|-------|--------|----------|----------|------|
| AI-Backend-1 | TS-ERR-001 | src/api/controllers/ImageRecognitionController.ts, src/api/controllers/NaturalLanguageProcessingController.ts, src/api/controllers/RecommendationController.ts, src/api/routes/operation-agent.ts, src/api/routes/product.ts, src/core/ai/MerchantAnalysisService.ts, src/core/ai/MerchantPredictionService.ts, src/core/ai/ReturnAnalysisService.ts, src/core/ai/ReturnOptimizationService.ts, src/core/ai/SettlementOptimizationService.ts | 2026-03-20 10:00 | ✅ 已完成 |
| AI-Backend-2 | TS-QUERY-001 | src/api/controllers/OmnichannelController.ts, src/api/controllers/SettingsController.ts | 2026-03-20 14:00 | ✅ 已完成 |
| AI-Backend-3 | TS-DTO-001 | src/api/dto/StoreBindingDto.ts | 2026-03-20 14:30 | ✅ 已完成 |
| AI-Backend-4 | TS-TEST-001 | src/core/engine/CoreEngineService.test.ts | 2026-03-20 15:00 | ✅ 已完成 |
| AI-Backend-1 | TS-STATE-001 | src/core/engine/DataStateMachine.ts, src/core/engine/OrderStateMachine.ts, src/core/engine/ProductStateMachine.ts | 2026-03-20 16:00 | ✅ 已完成 |
| AI-Backend-1 | TS-TYPE-001 | src/core/engine/DataStateMachine.ts, src/core/engine/OrderStateMachine.ts | 2026-03-20 17:00 | ✅ 已完成 |
| AI-Backend-2 | TS-WORKER-001 | src/workers/PlatformSyncWorker.ts | 2026-03-20 18:00 | ✅ 已完成 |
---
## <20>📊 错误分类统计
| 错误类型 | 错误码 | 数量 | 优先级 | 状态 |
|---------|--------|------|--------|------|
| **error is of type 'unknown'** | TS18046 | ~30 | 🔴 高 | ✅ 已完成 |
| **string \| string[] 类型不匹配** | TS2345/TS2322 | ~60 | 🔴 高 | 🔒 进行中 |
| **Property has no initializer** | TS2564 | 5 | 🟡 中 | ✅ 已完成 |
| **Property does not exist** | TS2339 | ~10 | 🟡 中 | ✅ 已完成 |
| **StateMachine not callable** | TS2348 | 3 | 🟡 中 | ✅ 已完成 |
| **Type 'string[]' not assignable** | TS2322 | 2 | 🟡 中 | ✅ 已完成 |
---
## 🔴 任务包 1error 类型修复TS18046
### 任务ID: TS-ERR-001
**错误描述**: `'error' is of type 'unknown'`
**涉及文件**:
| 文件 | 行号 | 状态 |
|------|------|------|
| `src/api/controllers/ImageRecognitionController.ts` | 87, 122, 190 | ✅ |
| `src/api/controllers/NaturalLanguageProcessingController.ts` | 88, 124, 210 | ✅ |
| `src/api/controllers/RecommendationController.ts` | 92, 120, 161, 209, 224 | ✅ |
| `src/api/routes/operation-agent.ts` | 31, 42 | ✅ |
| `src/api/routes/product.ts` | 29, 40 | ✅ |
| `src/core/ai/MerchantAnalysisService.ts` | 142, 186 | ✅ |
| `src/core/ai/MerchantPredictionService.ts` | 85, 136 | ✅ |
| `src/core/ai/ReturnAnalysisService.ts` | 101, 160 | ✅ |
| `src/core/ai/ReturnOptimizationService.ts` | 97 | ✅ |
| `src/core/ai/SettlementOptimizationService.ts` | 81, 157 | ✅ |
**修复方案**:
```typescript
// ❌ 错误
catch (error) {
console.error(error.message)
}
// ✅ 正确
catch (error: unknown) {
if (error instanceof Error) {
console.error(error.message)
}
}
// 或使用类型守卫
catch (error) {
const message = error instanceof Error ? error.message : String(error)
console.error(message)
}
```
**领取模板**:
```markdown
### 🔒 任务领取声明
**Agent**: [你的标识]
**领取时间**: [YYYY-MM-DD HH:MM]
**任务ID**: TS-ERR-001
**涉及文件**: [列出你要修复的文件]
```
---
## 🔴 任务包 2req.query 类型修复TS2345/TS2322
### 任务ID: TS-QUERY-001
**错误描述**: `Argument of type 'string | string[]' is not assignable to parameter of type 'string'`
**涉及文件**:
| 文件 | 错误数 | 状态 |
|------|--------|------|
| `src/api/controllers/OmnichannelController.ts` | ~25 | 🔒 |
| `src/api/controllers/SettingsController.ts` | ~35 | 🔒 |
**修复方案**:
```typescript
// ❌ 错误
const id = req.query.id as string
// ✅ 正确 - 方案1类型守卫
const id = Array.isArray(req.query.id) ? req.query.id[0] : req.query.id
// ✅ 正确 - 方案2工具函数
function getQueryParam(value: string | string[] | undefined): string | undefined {
if (Array.isArray(value)) return value[0]
return value
}
const id = getQueryParam(req.query.id)
// ✅ 正确 - 方案3强制断言确定不会是数组时
const id = req.query.id as string | undefined
```
**领取模板**:
```markdown
### 🔒 任务领取声明
**Agent**: [你的标识]
**领取时间**: [YYYY-MM-DD HH:MM]
**任务ID**: TS-QUERY-001
**涉及文件**: [列出你要修复的文件]
```
---
## 🟡 任务包 3DTO 属性初始化修复TS2564
### 任务ID: TS-DTO-001
**错误描述**: `Property 'xxx' has no initializer and is not definitely assigned in the constructor`
**涉及文件**:
| 文件 | 行号 | 属性 | 状态 |
|------|------|------|------|
| `src/api/dto/StoreBindingDto.ts` | 2 | merchantId | ✅ |
| `src/api/dto/StoreBindingDto.ts` | 3 | platform | ✅ |
| `src/api/dto/StoreBindingDto.ts` | 4 | platformShopId | ✅ |
| `src/api/dto/StoreBindingDto.ts` | 5 | name | ✅ |
| `src/api/dto/StoreBindingDto.ts` | 7 | authInfo | ✅ |
**修复方案**:
```typescript
// ❌ 错误
class StoreBindingDto {
merchantId: string
platform: string
}
// ✅ 正确 - 方案1添加默认值
class StoreBindingDto {
merchantId: string = ''
platform: string = ''
}
// ✅ 正确 - 方案2使用可选属性
class StoreBindingDto {
merchantId?: string
platform?: string
}
// ✅ 正确 - 方案3使用 definite assignment assertion
class StoreBindingDto {
merchantId!: string
platform!: string
}
```
**领取模板**:
```markdown
### 🔒 任务领取声明
**Agent**: [你的标识]
**领取时间**: [YYYY-MM-DD HH:MM]
**任务ID**: TS-DTO-001
**涉及文件**: src/api/dto/StoreBindingDto.ts
```
---
## 🟡 任务包 4测试文件类型修复TS2345/TS2339
### 任务ID: TS-TEST-001
**错误描述**: 测试文件中的类型不匹配
**涉及文件**:
| 文件 | 行号 | 错误类型 | 状态 |
|------|------|---------|------|
| `src/core/engine/CoreEngineService.test.ts` | 27, 82, 85 | 缺少 data 属性 | ✅ |
| `src/core/engine/CoreEngineService.test.ts` | 30-33 | 属性不存在 | ✅ |
**修复方案**:
```typescript
// ❌ 错误
const request = { id: 'test', type: 'order' }
const result = engine.process(request)
expect(result.validated).toBe(true)
// ✅ 正确
const request: BusinessRequest = {
id: 'test',
type: 'order',
data: {} // 添加必需的 data 属性
}
const result = engine.process(request)
expect(result.status.validated).toBe(true) // 使用正确的属性路径
```
**领取模板**:
```markdown
### 🔒 任务领取声明
**Agent**: [你的标识]
**领取时间**: [YYYY-MM-DD HH:MM]
**任务ID**: TS-TEST-001
**涉及文件**: src/core/engine/CoreEngineService.test.ts
```
---
## 🟡 任务包 5StateMachine 构造函数修复TS2348
### 任务ID: TS-STATE-001
**错误描述**: `Value of type 'typeof StateMachine' is not callable. Did you mean to include 'new'?`
**涉及文件**:
| 文件 | 行号 | 状态 |
|------|------|------|
| `src/core/engine/DataStateMachine.ts` | 31 | ✅ |
| `src/core/engine/OrderStateMachine.ts` | 31 | ✅ |
| `src/core/engine/ProductStateMachine.ts` | 29 | ✅ |
**修复方案**:
```typescript
// ❌ 错误
const machine = StateMachine(initialState, config)
// ✅ 正确
const machine = new StateMachine(initialState, config)
```
**领取模板**:
```markdown
### 🔒 任务领取声明
**Agent**: [你的标识]
**领取时间**: [YYYY-MM-DD HH:MM]
**任务ID**: TS-STATE-001
**涉及文件**: [列出你要修复的文件]
```
---
## 🟡 任务包 6状态类型数组修复TS2322
### 任务ID: TS-TYPE-001
**错误描述**: `Type 'string[]' is not assignable to type 'xxx[]'`
**涉及文件**:
| 文件 | 行号 | 状态 |
|------|------|------|
| `src/core/engine/DataStateMachine.ts` | 131 | ✅ |
| `src/core/engine/OrderStateMachine.ts` | 139 | ✅ |
**修复方案**:
```typescript
// ❌ 错误
const events: string[] = ['RETRY', 'VALID', 'PROCESS']
// ✅ 正确
type DataEvent = 'RETRY' | 'VALID' | 'VALIDATE' | 'INVALID' | 'PROCESS' | 'PROCESS_SUCCESS' | 'PROCESS_ERROR'
const events: DataEvent[] = ['RETRY', 'VALID', 'PROCESS']
// 或使用 as const
const events = ['RETRY', 'VALID', 'PROCESS'] as const
```
**领取模板**:
```markdown
### 🔒 任务领取声明
**Agent**: [你的标识]
**领取时间**: [YYYY-MM-DD HH:MM]
**任务ID**: TS-TYPE-001
**涉及文件**: [列出你要修复的文件]
```
---
## 🟡 任务包 7WorkerHub 属性修复TS2339
### 任务ID: TS-WORKER-001
**错误描述**: `Property 'addJob' does not exist on type 'typeof WorkerHub'`
**涉及文件**:
| 文件 | 行号 | 状态 |
|------|------|------|
| `src/workers/PlatformSyncWorker.ts` | 288 | ✅ |
**修复方案**:
```typescript
// 需要检查 WorkerHub 类定义,确保 addJob 方法存在且为静态方法
// 或修改为实例方法调用
```
**领取模板**:
```markdown
### 🔒 任务领取声明
**Agent**: [你的标识]
**领取时间**: [YYYY-MM-DD HH:MM]
**任务ID**: TS-WORKER-001
**涉及文件**: src/workers/PlatformSyncWorker.ts
```
---
## 📋 任务领取规则
### 领取原则
1. **优先领取任务包**:必须优先领取同一类型的完整任务包
2. **最小粒度**:单次领取不少于 1 个任务包
3. **文件锁定**:同一文件同时只能被一个 Agent 修改
### 领取流程
1. 在本文档顶部更新 🔒 当前占用区
2. 修改对应任务的状态为 🔒 进行中
3. 完成后更新状态为 ✅ 已完成
4. 释放文件占用
---
## 🔒 当前任务占用状态
| Agent | 任务ID | 涉及文件 | 开始时间 | 状态 |
|-------|--------|----------|----------|------|
| AI-Backend-1 | TS-TEST-002 | src/tests/integration/IntegrationTestCases.ts, src/tests/integration/plugin.integration.test.ts, src/tests/integration/tuple-tracing.test.ts, src/tests/qa/TestDatabaseInitializer.ts, src/tests/unit/UnitTestCases.ts | 2026-03-21 10:00 | 🔒 进行中 |
---
## 📈 修复进度
| 任务包 | 总数 | 已完成 | 进度 |
|--------|------|--------|------|
| TS-ERR-001 | ~30 | 30 | 100% |
| TS-QUERY-001 | ~60 | 60 | 100% |
| TS-DTO-001 | 5 | 5 | 100% |
| TS-TEST-001 | 8 | 8 | 100% |
| TS-STATE-001 | 3 | 3 | 100% |
| TS-TYPE-001 | 2 | 2 | 100% |
| TS-WORKER-001 | 1 | 1 | 100% |
| **总计** | **~109** | **109** | **100%** |
---
*本文档将持续更新,记录修复进度。*