TypeScript 最佳实践指南
在大型项目中使用 TypeScript 可以显著提高代码质量和开发效率。本文分享一些实用的最佳实践和经验教训。
类型定义策略
接口 vs 类型别名
typescript// 推荐使用接口来定义对象形状
interface User {
id: number
name: string
email: string
}
// 对于联合类型或原始类型使用类型别名
type Status = 'active' | 'inactive' | 'pending'
type ID = string | number
泛型使用
typescript// API 响应的泛型接口
interface ApiResponse
data: T
message: string
success: boolean
}
// 使用示例
interface User {
id: number
name: string
}
const response: ApiResponse
data: { id: 1, name: 'John' },
message: 'Success',
success: true
}
配置优化
tsconfig.json 最佳配置
json{
"compilerOptions": {
"target": "ES2020",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"]
}
实用模式
条件类型
typescripttype NonNullable
type Example = NonNullable
映射类型
typescripttype Optional
[P in keyof T]?: T[P]
}
interface User {
id: number
name: string
email: string
}
type OptionalUser = Optional
// { id?: number, name?: string, email?: string }
错误处理
自定义错误类型
typescriptclass ValidationError extends Error {
constructor(message: string, public field: string) {
super(message)
this.name = 'ValidationError'
}
}
class NetworkError extends Error {
constructor(message: string, public statusCode: number) {
super(message)
this.name = 'NetworkError'
}
}
function handleError(error: Error) {
if (error instanceof ValidationError) {
console.log(`Validation failed for field: ${error.field}`)
} else if (error instanceof NetworkError) {
console.log(`Network error with status: ${error.statusCode}`)
}
}
总结
良好的 TypeScript 实践可以让大型项目更加可维护和可扩展。记住:
1. 使用严格模式
2. 合理定义接口和类型
3. 充分利用泛型
4. 编写可测试的代码
5. 保持类型定义的 DRY 原则
通过遵循这些最佳实践,你可以充分发挥 TypeScript 的优势,构建出高质量的应用程序。