typescript编程规范
TypeScript 编程规范的核心要点综合了 Google、Microsoft 及社区最佳实践一、命名规范表格类型规范示例变量/函数/参数camelCasegetUserInfo,userName类/接口/类型/枚举PascalCaseUserService,UserData常量UPPER_SNAKE_CASEMAX_USERS接口成员camelCase不使用I前缀枚举成员PascalCaseSyntaxKind.StringLiteral注意接口不要使用I前缀TypeScript 官方库如Window、Document都不使用I前缀。二、类型与类型安全1. 启用严格模式在tsconfig.json中必须启用strict: true这是类型安全的基础。JSON复制{ compilerOptions: { target: ES2022, module: NodeNext, strict: true, esModuleInterop: true, skipLibCheck: true, forceConsistentCasingInFileNames: true, noEmitOnError: true } }2. 避免使用any使用unknown 类型守卫替代any确保运行时安全。TypeScript复制// ❌ 避免 function process(data: any) { ... } // ✅ 推荐 function process(data: unknown) { if (typeof data string) { // 安全使用 data } }3. 类型断言使用as语法而非尖括号语法且必须添加注释说明原因。TypeScript复制// ❌ 避免 const x (Fooz).length; // ✅ 推荐 // z 必须是 Foo因为 ... const x (z as Foo).length;4. 优先使用undefined而非null除非 API 约定使用null如 Node.js 回调否则优先使用undefined。TypeScript复制// ❌ 避免 let foo { x: 123, y: undefined }; // ✅ 推荐 let foo: { x: number; y?: number } { x: 123 };三、函数规范1. 使用箭头函数表达式中优先使用箭头函数避免function关键字。TypeScript复制// ❌ 避免 bar(function() { ... }); // ✅ 推荐 bar(() { this.doSomething(); });2. 函数参数使用对象形式当参数超过一个时使用对象参数提高可读性和可扩展性。TypeScript复制// ❌ 避免 transformUserInput(client, false, 60, 120, null, true, 2000); // ✅ 推荐 transformUserInput({ method: client, isValidated: false, minLines: 60, maxLines: 120, defaultInput: null, shouldLog: true, timeout: 2000, });3. 纯函数与单一职责函数应该是纯函数相同输入始终返回相同输出函数应该无状态、无副作用函数应该单一职责四、类与可见性1. 限制可见性尽可能限制符号的可见性TypeScript 默认public不需要显式声明。TypeScript复制// ❌ 避免 class Foo { public bar new Bar(); constructor(public readonly baz: Baz) {} } // ✅ 推荐 class Foo { bar new Bar(); constructor(public baz: Baz) {} }2. 避免在静态方法中使用this静态方法中不应使用this静态字段也不应通过this访问。TypeScript复制// ❌ 避免 class ShoeStore { static storage: Storage ...; static isAvailable(s: Shoe) { return this.storage.has(s.id); // Bad } } // ✅ 推荐 class ShoeStore { static storage: Storage ...; static isAvailable(s: Shoe) { return ShoeStore.storage.has(s.id); } }五、代码格式表格规范推荐值缩进2 个空格不使用 Tab引号单引号分号必须使用分号不依赖 ASI数组注解Foo[]而非ArrayFoo文件编码UTF-8六、控制流与迭代1. 避免for...in使用for...of Object.keys()或for...of Object.entries()替代。TypeScript复制// ❌ 避免 for (const x in someObj) { ... } // ✅ 推荐 for (const x of Object.keys(someObj)) { ... } for (const [key, value] of Object.entries(someObj)) { ... }2. 多行控制流必须使用代码块TypeScript复制// ❌ 避免 if (x) x.doFoo(); for (let i 0; i x; i) doSomething(i); // ✅ 推荐 if (x) { x.doFoo(); } for (let i 0; i x; i) { doSomething(i); }七、不可变性与数据安全1. 使用const和readonly默认使用const数组和对象使用Readonly/ReadonlyArray。TypeScript复制// ❌ 避免数据突变 const removeFirstUser (users: ArrayUser) { return users.splice(1); }; // ✅ 推荐 const removeFirstUser (users: ReadonlyArrayUser) { return users.slice(1); // splice 会报错 };2. 使用 discriminated unions可辨识联合当对象有很多可选属性时使用可辨识联合替代。TypeScript复制// ❌ 避免过多可选属性 type User { id?: number; email?: string; adminPermissions?: string[]; }; // ✅ 推荐 type AdminUser { role: admin; id: number; adminPermissions: string[] }; type RegularUser { role: regular; id: number; email: string }; type User AdminUser | RegularUser;八、工程化最佳实践表格实践说明共享类型定义统一类型文件管理公共接口CI 强制类型检查类型检查作为代码提交的必要条件使用 ESLint Prettier自动化代码格式和规则检查渐进式迁移JS 项目逐步迁移.js→ts-check→.ts→strict避免过度复杂类型复杂条件类型会影响编译性能九、禁止使用的特性表格特性原因var函数作用域导致难以理解的 Bugconst enum对 JavaScript 用户不可见eval()/Function(string)安全隐患CSP 不兼容with严格模式已禁止debugger不应出现在生产代码包装对象new String()等行为异常如new Boolean(false)为true直接操作prototype使用class关键字更清晰十、推荐的工具链配置JSON复制// tsconfig.json { compilerOptions: { target: ES2022, module: NodeNext, strict: true, esModuleInterop: true, skipLibCheck: true, forceConsistentCasingInFileNames: true, noEmitOnError: true, noUnusedLocals: true, noUnusedParameters: true, noImplicitReturns: true, noFallthroughCasesInSwitch: true } }配合typescript-eslint的strict-type-checked配置使用效果更佳。