元素码农
基础
UML建模
数据结构
算法
设计模式
网络
TCP/IP协议
HTTPS安全机制
WebSocket实时通信
数据库
sqlite
postgresql
clickhouse
后端
rust
go
java
php
mysql
redis
mongodb
etcd
nats
zincsearch
前端
浏览器
javascript
typescript
vue3
react
游戏
unity
unreal
C++
C#
Lua
App
android
ios
flutter
react-native
安全
Web安全
测试
软件测试
自动化测试 - Playwright
人工智能
Python
langChain
langGraph
运维
linux
docker
工具
git
svn
🌞
🌙
目录
▶
TypeScript环境准备
安装与配置
第一个TS程序
编译流程解析
▶
基础类型系统
类型注解语法
原始类型定义
数组与元组
接口与对象
▶
高级类型系统
泛型编程
条件类型
映射类型
类型推断
类型保护
高级类型工具
▶
函数开发
函数类型声明
可选参数与默认值
箭头函数应用
函数重载
泛型函数
▶
类与面向对象
类的定义
继承与修饰符
存取器使用
抽象类与接口
泛型类与抽象类
访问修饰符与属性
▶
模块化开发
模块导入导出
类型声明文件
命名空间
模块解析策略
▶
工程实践
tsconfig详解
常见编译选项
项目构建配置
代码组织最佳实践
单元测试
调试技巧
▶
常见问题
类型错误处理
类型断言技巧
类型兼容性
版本迁移指南
发布时间:
2025-03-31 09:49
↑
☰
# TypeScript代码组织最佳实践 本文将介绍TypeScript项目的代码组织最佳实践,帮助你建立一个清晰、可维护的项目结构。我们将从项目结构、命名规范、模块化设计等多个方面进行详细讨论。 ## 项目目录结构 ### 基础目录结构 ``` src/ ├── assets/ # 静态资源 ├── components/ # UI组件 ├── config/ # 配置文件 ├── constants/ # 常量定义 ├── hooks/ # 自定义Hook ├── interfaces/ # 类型定义 ├── services/ # API服务 ├── store/ # 状态管理 ├── utils/ # 工具函数 └── views/ # 页面组件 ``` ### 特性化目录结构 ``` src/ ├── features/ # 业务功能模块 │ ├── auth/ # 认证模块 │ │ ├── components/ │ │ ├── hooks/ │ │ ├── services/ │ │ └── types/ │ └── user/ # 用户模块 │ ├── components/ │ ├── hooks/ │ ├── services/ │ └── types/ └── shared/ # 共享模块 ├── components/ ├── hooks/ └── utils/ ``` ## 命名规范 ### 1. 文件命名 ```typescript // 组件文件使用PascalCase UserProfile.tsx LoginForm.tsx // 工具函数、Hook使用camelCase useAuth.ts formatDate.ts // 类型定义文件使用.d.ts后缀 types.d.ts api.d.ts ``` ### 2. 变量命名 ```typescript // 接口名使用I前缀或Interface后缀 interface IUser { id: number; name: string; } // 类型别名使用T前缀或Type后缀 type TApiResponse<T> = { data: T; status: number; }; // 常量使用大写下划线 const MAX_RETRY_COUNT = 3; const API_BASE_URL = 'https://api.example.com'; ``` ## 模块化设计 ### 1. 单一职责原则 ```typescript // 好的实践 class UserService { async getUser(id: number): Promise<User> { /* ... */ } async updateUser(user: User): Promise<void> { /* ... */ } } // 避免的实践 class UserService { async getUser(id: number): Promise<User> { /* ... */ } async sendEmail(to: string): Promise<void> { /* ... */ } // 应该移到EmailService } ``` ### 2. 模块导出 ```typescript // index.ts作为模块入口 export * from './types'; export * from './constants'; export { default as UserService } from './UserService'; // 避免循环依赖 // 使用依赖注入或重构代码结构 ``` ## 类型组织 ### 1. 集中管理类型 ```typescript // src/types/index.ts export interface User { id: number; name: string; email: string; } export type UserRole = 'admin' | 'user' | 'guest'; export interface ApiResponse<T> { data: T; message: string; status: number; } ``` ### 2. 特性相关类型 ```typescript // src/features/auth/types.ts export interface LoginCredentials { username: string; password: string; } export interface AuthState { user: User | null; token: string | null; isAuthenticated: boolean; } ``` ## 状态管理 ### 1. 状态分层 ```typescript // 全局状态 interface RootState { auth: AuthState; theme: ThemeState; // ... } // 特性状态 interface AuthState { user: User | null; token: string | null; } // 组件状态 const [isLoading, setIsLoading] = useState(false); ``` ### 2. 状态访问 ```typescript // 使用自定义Hook封装状态访问 function useAuth() { const user = useSelector((state: RootState) => state.auth.user); const dispatch = useDispatch(); const login = useCallback(async (credentials: LoginCredentials) => { // 处理登录逻辑 }, [dispatch]); return { user, login }; } ``` ## 错误处理 ### 1. 统一错误类型 ```typescript class AppError extends Error { constructor( message: string, public code: string, public status: number = 500 ) { super(message); this.name = 'AppError'; } } // 使用示例 throw new AppError('User not found', 'USER_NOT_FOUND', 404); ``` ### 2. 错误边界 ```typescript class ErrorBoundary extends React.Component<Props, State> { static getDerivedStateFromError(error: Error) { return { hasError: true, error }; } render() { if (this.state.hasError) { return <ErrorFallback error={this.state.error} />; } return this.props.children; } } ``` ## 性能优化 ### 1. 代码分割 ```typescript // 路由级别的代码分割 const UserProfile = React.lazy(() => import('./features/user/UserProfile')); // 组件级别的代码分割 const HeavyComponent = React.lazy(() => import('./components/HeavyComponent')); ``` ### 2. 性能监控 ```typescript // 使用自定义Hook监控性能 function usePerformanceMonitor(componentName: string) { useEffect(() => { const startTime = performance.now(); return () => { const endTime = performance.now(); console.log(`${componentName} rendered in ${endTime - startTime}ms`); }; }, [componentName]); } ``` ## 测试组织 ### 1. 测试目录结构 ``` src/ ├── components/ │ ├── Button/ │ │ ├── Button.tsx │ │ ├── Button.test.tsx │ │ └── Button.stories.tsx └── utils/ ├── format.ts └── format.test.ts ``` ### 2. 测试命名 ```typescript describe('UserService', () => { describe('getUser', () => { it('should return user when valid id is provided', () => { // 测试代码 }); it('should throw error when user not found', () => { // 测试代码 }); }); }); ``` ## 总结 良好的代码组织可以: - 提高代码可维护性 - 增强团队协作效率 - 降低开发成本 - 提升代码质量 建议根据项目规模和团队情况,选择合适的代码组织方式,并在实践中不断优化和改进。记住保持一致性和可预测性是代码组织的关键原则。