# Using ESLint and Prettier with TypeScript

To maintain code quality and consistent formatting in a TypeScript project, it is standard practice to use **ESLint** (for code quality/logic errors) and **Prettier** (for styling/formatting) together.

## 1. Installation

You need to install the core tools, the TypeScript-specific parsers, and the plugins that make them play nicely together.

```bash
npm install --save-dev eslint prettier @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-config-prettier eslint-plugin-prettier
```

*   **eslint**: The core linter.
*   **prettier**: The core formatter.
*   **@typescript-eslint/parser**: Allows ESLint to understand TypeScript syntax.
*   **@typescript-eslint/eslint-plugin**: Contains specific linting rules for TypeScript.
*   **eslint-config-prettier**: Disables ESLint rules that might conflict with Prettier.
*   **eslint-plugin-prettier**: Runs Prettier as an ESLint rule.

## 2. Configure Prettier

Create a `.prettierrc` file in your project root to define your formatting rules.

```json
{
  "semi": true,
  "trailingComma": "all",
  "singleQuote": true,
  "printWidth": 100,
  "tabWidth": 2
}
```

## 3. Configure ESLint

Create an `.eslintrc.json` (or `.eslintrc.js`) file in your project root.

```json
{
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaVersion": 2020,
    "sourceType": "module"
  },
  "extends": [
    "plugin:@typescript-eslint/recommended",
    "plugin:prettier/recommended"
  ],
  "rules": {
    // You can override specific rules here
    "@typescript-eslint/no-explicit-any": "off"
  }
}
```

**Important:** The `"plugin:prettier/recommended"` line must be the **last** item in the `extends` array. This ensures Prettier overrides other configs.

## 4. VS Code Integration

To have your code fixed automatically when you save, install the **VS Code ESLint extension** and create a `.vscode/settings.json` file in your project:

```json
{
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "eslint.validate": [
    "javascript",
    "typescript"
  ]
}
```

With this setup, when you save a file:
1.  Prettier formats the code (via ESLint).
2.  ESLint fixes any auto-fixable logic errors.

## 5. Add Scripts to package.json

Add these scripts to easily run checks from the command line (useful for CI/CD).

```json
"scripts": {
  "lint": "eslint 'src/**/*.{ts,js}'",
  "lint:fix": "eslint 'src/**/*.{ts,js}' --fix",
  "format": "prettier --write 'src/**/*.{ts,js,json,md}'"
}
```

[[programming/javascript/typescript/typescript]]
[[programming/javascript/typescript/setup-node-project]]