---
description: TypeScript 严格类型安全和代码规范
globs: ["**/*.ts", "**/*.tsx"]
alwaysApply: true
---

# TypeScript 代码规范

## 🎯 严格类型安全要求

### 必须启用的 TypeScript 配置
```json
{
  "compilerOptions": {
    "strict": true,
    "strictNullChecks": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "exactOptionalPropertyTypes": true
  }
}
```

### 禁用 any 类型
```typescript
// ❌ 禁止使用 any
const data: any = fetchData();

// ✅ 使用具体类型或泛型
interface ApiResponse<T> {
  data: T;
  status: number;
  message: string;
}

const data: ApiResponse<User> = await fetchUserData();

// ✅ 未知类型使用 unknown
const parseJSON = (json: string): unknown => {
  return JSON.parse(json);
};
```

## 📝 类型注解规范

### 函数参数和返回值
```typescript
// ✅ 必须明确指定类型
const calculateTotal = (items: ProductItem[], discountRate: number): number => {
  const subtotal = items.reduce((sum, item) => sum + item.price, 0);
  return subtotal * (1 - discountRate);
};

// ✅ 异步函数类型
const fetchUserData = async (userId: string): Promise<User | null> => {
  try {
    const response = await api.get(`/users/${userId}`);
    return response.data;
  } catch (error) {
    console.error("获取用户数据失败:", error);
    return null;
  }
};
```

### 接口定义规范
```typescript
// ✅ PascalCase 命名，以 I 开头
interface IUser {
  readonly id: string; // 只读属性
  firstName: string; // 必需属性
  lastName: string;
  email?: string; // 可选属性
  permissions: Permission[]; // 数组类型
  createdAt: Date;
  updatedAt?: Date;
}

// ✅ 继承和组合
interface IAdminUser extends IUser {
  adminLevel: AdminLevel;
  canDeleteUsers: boolean;
}
```

### null 和 undefined 处理
```typescript
// ✅ 明确标注可能为空的值
const findUserById = (id: string): User | null => {
  const user = users.find((u) => u.id === id);
  return user || null;
};

// ✅ 使用可选链和空值合并
const getUserDisplayName = (user: User | null): string => {
  return user?.firstName ?? "未知用户";
};
```

## 🚫 禁用枚举（enum）

### 禁止使用 TypeScript 枚举
```typescript
// ❌ 禁止使用枚举
enum UserRole {
  ADMIN = 'admin',
  USER = 'user',
  GUEST = 'guest'
}

enum OrderStatus {
  PENDING = 0,
  PROCESSING = 1,
  COMPLETED = 2,
  CANCELLED = 3
}
```

### 使用常量对象替代枚举
```typescript
// ✅ 使用常量对象替代枚举
const USER_ROLE = {
  ADMIN: 'admin',
  USER: 'user',
  GUEST: 'guest'
} as const;

const ORDER_STATUS = {
  PENDING: 0,
  PROCESSING: 1,
  COMPLETED: 2,
  CANCELLED: 3
} as const;

// ✅ 提供对应的类型定义
type UserRole = typeof USER_ROLE[keyof typeof USER_ROLE];
type OrderStatus = typeof ORDER_STATUS[keyof typeof ORDER_STATUS];

// ✅ 使用示例
const currentRole: UserRole = USER_ROLE.ADMIN;
const hasPermission = (role: UserRole): boolean => {
  return role === USER_ROLE.ADMIN;
};

const updateOrderStatus = (orderId: string, status: OrderStatus): void => {
  // 更新订单状态逻辑
  console.log(`订单 ${orderId} 状态更新为: ${status}`);
};
```

### 常量对象的优势
1. **更好的类型推断**：`as const` 确保类型推断的准确性
2. **更小的打包体积**：不会生成额外的 JavaScript 代码
3. **更好的 Tree Shaking**：未使用的常量可以被正确移除
4. **更灵活的使用方式**：可以直接作为值使用，也可以作为类型使用
5. **更好的 IDE 支持**：提供更好的自动补全和重构支持