阿里云主机折上折
  • 微信号
Current Site:Index > Code standards and lint tools

Code standards and lint tools

Author:Chuan Chen 阅读数:59316人阅读 分类: TypeScript

The Importance of Code Standards

Code standards are an indispensable part of team collaboration. A unified code style can significantly improve code readability and reduce maintenance costs, especially in large-scale projects. TypeScript, as a superset of JavaScript, inherits the flexibility of JS while introducing more scenarios that require standardization.

// Non-standard example
function getUserInfo(id:number){
  return {name:'John',age:30}
}

// Standard example
interface User {
  name: string;
  age: number;
}

function getUserInfo(id: number): User {
  return {
    name: 'John',
    age: 30,
  };
}

Common TypeScript Standard Points

Type Annotations

Explicit type annotations greatly enhance code maintainability. Even though TypeScript can infer types, it is recommended to add types for function parameters and return values.

// Not recommended
const add = (a, b) => a + b;

// Recommended
const add = (a: number, b: number): number => a + b;

Interfaces vs. Type Aliases

Prefer interfaces for defining object shapes, while type aliases are more suitable for union types or complex types.

// Interface
interface Point {
  x: number;
  y: number;
}

// Type alias
type Coordinates = Point | null;

Enum Usage

Numeric enums can easily cause issues. It is recommended to use string enums or constant union types.

// Not recommended
enum Status {
  Success,
  Error,
}

// Recommended
const enum Status {
  Success = 'SUCCESS',
  Error = 'ERROR',
}

Basic ESLint Configuration

ESLint is a mainstream linting tool for JavaScript/TypeScript. Configure .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-Specific Rules

Strict Null Checks

Enabling strictNullChecks can prevent many runtime errors.

// tsconfig.json
{
  "compilerOptions": {
    "strictNullChecks": true
  }
}

// Code example
let name: string;
name = null; // Compilation error

Limiting Type Assertions

Avoid using as type assertions; prefer type guards instead.

// Not recommended
const element = document.getElementById('root') as HTMLDivElement;

// Recommended
const element = document.getElementById('root');
if (!(element instanceof HTMLDivElement)) {
  throw new Error('Element not found or wrong type');
}

Prettier Integration

Prettier handles code formatting and works well with ESLint:

// .prettierrc
{
  "printWidth": 80,
  "tabWidth": 2,
  "singleQuote": true,
  "trailingComma": "es5",
  "semi": true
}

// Integration example
module.exports = {
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'prettier/@typescript-eslint',
    'plugin:prettier/recommended'
  ]
}

Custom Rule Development

When existing rules don't meet requirements, you can develop custom rules:

// no-console-time.ts
import { TSESLint } from '@typescript-eslint/utils';

const rule: TSESLint.RuleModule<'noConsoleTime', []> = {
  meta: {
    type: 'problem',
    docs: {
      description: 'Disallow the use of console.time/timeEnd',
    },
    messages: {
      noConsoleTime: 'Avoid using console.time; consider using the Performance API instead',
    },
  },
  create(context) {
    return {
      "CallExpression[callee.object.name='console'][callee.property.name=/^time|timeEnd$/]"(node) {
        context.report({
          node,
          messageId: 'noConsoleTime',
        });
      },
    };
  },
};

export default rule;

Pre-Commit Checks

Use Husky and lint-staged to automate checks before committing:

// package.json
{
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{ts,tsx}": [
      "eslint --fix",
      "prettier --write"
    ]
  }
}

Editor Real-Time Feedback

Configure VS Code for automatic fixes on save:

// .vscode/settings.json
{
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "eslint.validate": [
    "typescript",
    "typescriptreact"
  ]
}

Performance Optimization Tips

Linting can slow down in large projects. Optimize with these methods:

  1. Use .eslintignore to exclude unnecessary files
  2. Limit TypeScript project reference scope
  3. Run lint tasks in parallel
# .eslintignore
build/
dist/
node_modules/
*.d.ts

Team Standard Implementation Strategies

  1. Introduce linting tools early in new projects
  2. Migrate legacy projects gradually, starting by disabling all rules and enabling them one by one
  3. Include lint checks in code reviews
  4. Regularly update rule sets to maintain consistency
// Gradual migration example
module.exports = {
  rules: {
    '@typescript-eslint/no-explicit-any': 'off', // Temporarily disabled
    '@typescript-eslint/no-unused-vars': 'warn' // Start with warnings
  }
};

Common Issue Resolution

Handling Rule Conflicts

When ESLint and Prettier rules conflict:

// Solution
module.exports = {
  extends: [
    'prettier', // Must be placed last
  ]
};

Handling Type Definition Files

Add type declarations for third-party libraries:

// global.d.ts
declare module 'untyped-module' {
  const value: any;
  export default value;
}

Advanced Type Checking

Leverage TypeScript advanced types to enhance code safety:

// Conditional type example
type NonNullable<T> = T extends null | undefined ? never : T;

// Mapped type example
type Readonly<T> = {
  readonly [P in keyof T]: T[P];
};

// Template literal types
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
type ApiEndpoint = `/api/${string}`;

Automated Documentation Generation

Generate type documentation with TSDoc:

/**
 * Basic user information
 * @remarks
 * Contains user identification details
 */
interface UserProfile {
  /** Unique user ID */
  id: string;
  /** Display name */
  displayName: string;
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.