代码规范与lint工具
代码规范的重要性
代码规范是团队协作中不可或缺的一环。统一的代码风格能显著提升代码可读性,降低维护成本,特别是在大型项目中。TypeScript作为JavaScript的超集,继承了JS灵活性的同时也带来了更多需要规范的场景。
// 不规范示例
function getUserInfo(id:number){
return {name:'John',age:30}
}
// 规范示例
interface User {
name: string;
age: number;
}
function getUserInfo(id: number): User {
return {
name: 'John',
age: 30,
};
}
常见TypeScript规范要点
类型注解
显式类型注解能极大提升代码可维护性。即使TypeScript能推断类型,也建议为函数参数和返回值添加类型。
// 不推荐
const add = (a, b) => a + b;
// 推荐
const add = (a: number, b: number): number => a + b;
接口与类型别名
优先使用接口定义对象形状,类型别名更适合联合类型或复杂类型。
// 接口
interface Point {
x: number;
y: number;
}
// 类型别名
type Coordinates = Point | null;
枚举使用
数字枚举容易引发问题,建议使用字符串枚举或常量联合类型。
// 不推荐
enum Status {
Success,
Error,
}
// 推荐
const enum Status {
Success = 'SUCCESS',
Error = 'ERROR',
}
ESLint基础配置
ESLint是主流的JavaScript/TypeScript lint工具。配置.eslintrc.js
:
module.exports = {
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
],
rules: {
'@typescript-eslint/explicit-function-return-type': 'warn',
'@typescript-eslint/no-explicit-any': 'error',
'semi': ['error', 'always'],
},
};
TypeScript专属规则
严格空检查
启用strictNullChecks
能避免许多运行时错误。
// tsconfig.json
{
"compilerOptions": {
"strictNullChecks": true
}
}
// 代码示例
let name: string;
name = null; // 编译错误
类型断言限制
避免使用as
类型断言,优先使用类型守卫。
// 不推荐
const element = document.getElementById('root') as HTMLDivElement;
// 推荐
const element = document.getElementById('root');
if (!(element instanceof HTMLDivElement)) {
throw new Error('Element not found or wrong type');
}
Prettier集成
Prettier处理代码格式化,与ESLint配合使用:
// .prettierrc
{
"printWidth": 80,
"tabWidth": 2,
"singleQuote": true,
"trailingComma": "es5",
"semi": true
}
// 集成配置示例
module.exports = {
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'prettier/@typescript-eslint',
'plugin:prettier/recommended'
]
}
自定义规则开发
当现有规则不满足需求时,可以开发自定义规则:
// no-console-time.ts
import { TSESLint } from '@typescript-eslint/utils';
const rule: TSESLint.RuleModule<'noConsoleTime', []> = {
meta: {
type: 'problem',
docs: {
description: '禁止使用console.time/timeEnd',
},
messages: {
noConsoleTime: '避免使用console.time,考虑使用性能API',
},
},
create(context) {
return {
"CallExpression[callee.object.name='console'][callee.property.name=/^time|timeEnd$/]"(node) {
context.report({
node,
messageId: 'noConsoleTime',
});
},
};
},
};
export default rule;
提交前检查
通过Husky和lint-staged实现提交前自动检查:
// package.json
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{ts,tsx}": [
"eslint --fix",
"prettier --write"
]
}
}
编辑器实时反馈
配置VS Code实现保存时自动修复:
// .vscode/settings.json
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.validate": [
"typescript",
"typescriptreact"
]
}
性能优化技巧
大型项目中lint可能变慢,可通过以下方式优化:
- 使用
.eslintignore
忽略不需要检查的文件 - 限制TypeScript项目引用范围
- 并行执行lint任务
# .eslintignore
build/
dist/
node_modules/
*.d.ts
团队规范实施策略
- 新项目初期就引入lint工具
- 老项目逐步迁移,先关闭所有规则然后逐个启用
- 代码审查中加入lint检查项
- 定期更新规则集保持一致性
// 渐进式迁移示例
module.exports = {
rules: {
'@typescript-eslint/no-explicit-any': 'off', // 暂时关闭
'@typescript-eslint/no-unused-vars': 'warn' // 先警告
}
};
常见问题解决
规则冲突处理
当ESLint与Prettier规则冲突时:
// 解决方案
module.exports = {
extends: [
'prettier', // 必须放在最后
]
};
类型定义文件处理
为第三方库添加类型声明:
// global.d.ts
declare module 'untyped-module' {
const value: any;
export default value;
}
高级类型检查
利用TypeScript高级类型增强代码安全性:
// 条件类型示例
type NonNullable<T> = T extends null | undefined ? never : T;
// 映射类型示例
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
// 模板字面量类型
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
type ApiEndpoint = `/api/${string}`;
自动化文档生成
结合TSDoc生成类型文档:
/**
* 用户基本信息
* @remarks
* 包含用户的标识信息
*/
interface UserProfile {
/** 用户唯一ID */
id: string;
/** 显示名称 */
displayName: string;
}
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:性能优化技巧
下一篇:与Webpack等构建工具集成