- typescript
---
description: TypeScript coding standards and best practices for modern web development
globs: **/*.ts, **/*.tsx, **/*.d.ts
---
# TypeScript Best Practices
## Type System
- Prefer interfaces over types for object definitions
- Use type for unions, intersections, and mapped types
- Avoid using `any`, prefer `unknown` for unknown types
- Use strict TypeScript configuration
- Leverage TypeScript's built-in utility types
- Use generics for reusable type patterns
## Naming Conventions
- Use PascalCase for type names and interfaces
- Use camelCase for variables and functions
- Use UPPER_CASE for constants
- Use descriptive names with auxiliary verbs (e.g., isLoading, hasError)
- Prefix interfaces for React props with 'Props' (e.g., ButtonProps)
## Code Organization
- Keep type definitions close to where they're used
- Export types and interfaces from dedicated type files when shared
- Use barrel exports (index.ts) for organizing exports
- Place shared types in a `types` directory
- Co-locate component props with their components
## Functions
- Use explicit return types for public functions
- Use arrow functions for callbacks and methods
- Implement proper error handling with custom error types
- Use function overloads for complex type scenarios
- Prefer async/await over Promises
## Best Practices
- Enable strict mode in tsconfig.json
- Use readonly for immutable properties
- Leverage discriminated unions for type safety
- Use type guards for runtime type checking
- Implement proper null checking
- Avoid type assertions unless necessary
## Error Handling
- Create custom error types for domain-specific errors
- Use Result types for operations that can fail
- Implement proper error boundaries
- Use try-catch blocks with typed catch clauses
- Handle Promise rejections properly
## Patterns
- Use the Builder pattern for complex object creation
- Implement the Repository pattern for data access
- Use the Factory pattern for object creation
- Leverage dependency injection
- Use the Module pattern for encapsulation
TypeScript 最佳实践
描述
现代 Web 开发的 TypeScript 编码标准和最佳实践
适用范围
/.ts, /.tsx, /.d.ts 目录下的所有文件
类型系统
- 对象定义优先使用接口而不是类型
- 对联合类型、交叉类型和映射类型使用 type
- 避免使用 any,对未知类型优先使用 unknown
- 使用严格的 TypeScript 配置
- 利用 TypeScript 的内置工具类型
- 使用泛型实现可重用的类型模式
命名约定
- 类型名称和接口使用 PascalCase
- 变量和函数使用 camelCase
- 常量使用 UPPER_CASE
- 使用带辅助动词的描述性名称
- React props 的接口名称前缀使用 'Props'
代码组织
- 将类型定义保持在使用位置附近
- 共享类型和接口从专用类型文件导出
- 使用桶导出(index.ts)组织导出
- 将共享类型放在 types 目录中
- 将组件 props 与其组件放在一起
函数
- 公共函数使用显式返回类型
- 回调和方法使用箭头函数
- 使用自定义错误类型实现适当的错误处理
- 复杂类型场景使用函数重载
- 优先使用 async/await 而不是 Promises
最佳实践
- 在 tsconfig.json 中启用严格模式
- 不可变属性使用 readonly
- 利用可辨识联合实现类型安全
- 使用类型守卫进行运行时类型检查
- 实现适当的空值检查
- 除非必要,否则避免类型断言
错误处理
- 为特定领域错误创建自定义错误类型
- 对可能失败的操作使用 Result 类型
- 实现适当的错误边界
- 使用带类型化 catch 子句的 try-catch 块
- 正确处理 Promise 拒绝
模式
- 使用构建器模式创建复杂对象
- 实现仓库模式进行数据访问
- 使用工厂模式创建对象
- 利用依赖注入
- 使用模块模式实现封装