TypeScript ESLint และ Prettier



แยกหน้าที่: ESLint จับบั๊ก/ปัญหา logic, Prettier จัดรูปแบบ (indent, quote, semicolon) — อย่าให้ ESLint จัดรูปแบบ

ติดตั้ง typescript-eslint

npm install --save-dev eslint typescript-eslint @eslint/js

eslint.config.js (flat config — ESLint 9+):

import js from "@eslint/js";
import tseslint from "typescript-eslint";

export default tseslint.config(
  js.configs.recommended,
  ...tseslint.configs.recommended,
  ...tseslint.configs.recommendedTypeChecked,   // type-aware rules
  {
    languageOptions: {
      parserOptions: {
        projectService: true,          // เชื่อมกับ tsconfig อัตโนมัติ
        tsconfigRootDir: import.meta.dirname,
      },
    },
    rules: {
      "@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_" }],
      "@typescript-eslint/consistent-type-imports": "error",   // บังคับ import type
      "@typescript-eslint/no-floating-promises": "error",
    },
  },
  {
    ignores: ["dist/", "node_modules/", "*.config.js"],
  },
);
// package.json
{
  "scripts": {
    "lint": "eslint .",
    "lint:fix": "eslint . --fix"
  }
}

type-aware rules — ต้องมี tsconfig

recommendedTypeChecked = rules ที่ต้องดู type จริง (ช้ากว่า syntax-only แต่ทรงพลัง):

// @typescript-eslint/no-floating-promises
saveData();   // Error: Promises must be awaited, end with a call to .catch, or be void

// @typescript-eslint/no-misused-promises
if (asyncFn()) { }   // Error: async ใน if condition (เป็น Promise เสมอ = truthy)

// @typescript-eslint/no-unnecessary-condition
const x: string = "hi";
if (x) { }   // Warn: condition เป็น true เสมอ (x ไม่มี null)

// @typescript-eslint/no-unsafe-assignment / -call / -member-access / -return
const data: any = fetch(...);
data.foo();   // Error: unsafe member access on any

// @typescript-eslint/require-await
async function f() { return 1; }   // Warn: async แต่ไม่มี await

// @typescript-eslint/switch-exhaustiveness-check
switch (action.type) { }   // Error ถ้าไม่ครบทุก case ของ discriminated union

no-floating-promises และ no-misused-promises เพียงสองอันนี้จับบั๊ก async ได้เยอะมาก

rules ที่แนะนำเพิ่ม

rules: {
  "@typescript-eslint/no-explicit-any": "warn",          // เตือนเมื่อเขียน any
  "@typescript-eslint/explicit-function-return-type": "off",  // ปล่อยให้ infer
  "@typescript-eslint/no-non-null-assertion": "warn",    // เตือน x!
  "@typescript-eslint/prefer-nullish-coalescing": "error",  // ?? แทน ||
  "@typescript-eslint/prefer-optional-chain": "error",
  "@typescript-eslint/no-unnecessary-type-assertion": "error",  // as ที่ไม่จำเป็น
  "@typescript-eslint/strict-boolean-expressions": "off",  // เข้มมาก (บางทีมเปิด)
  "eqeqeq": ["error", "always", { null: "ignore" }],     // === (แต่ == null OK)
  "no-console": ["warn", { allow: ["warn", "error"] }],
}

strict config (ทีมที่เอาจริง)

export default tseslint.config(
  js.configs.recommended,
  ...tseslint.configs.strictTypeChecked,      // เข้มกว่า recommended
  ...tseslint.configs.stylisticTypeChecked,   // stylistic (แต่ไม่ทับ Prettier)
  { /* parserOptions ... */ },
);

Prettier

npm install --save-dev prettier
// .prettierrc.json
{
  "semi": true,
  "singleQuote": false,
  "trailingComma": "all",
  "printWidth": 100,
  "tabWidth": 2
}
// package.json
{
  "scripts": {
    "format": "prettier --write .",
    "format:check": "prettier --check ."
  }
}

Prettier มีตัวเลือกน้อยโดยตั้งใจ — ทีมเลิกเถียงเรื่องรูปแบบ

ให้ ESLint กับ Prettier อยู่ด้วยกัน

ESLint 9 flat config + typescript-eslint recommended ไม่มี formatting rule ปนแล้ว (แยกไป stylistic) — ถ้าใช้ config เก่าหรือ plugin อื่นที่มี formatting rule ให้ปิดด้วย eslint-config-prettier:

npm install --save-dev eslint-config-prettier
import prettierConfig from "eslint-config-prettier";
export default tseslint.config(
  // ... configs อื่น
  prettierConfig,   // ปิด formatting rule ที่ชนกับ Prettier (ต้องอยู่ท้ายสุด)
);

editor + pre-commit

VS Code (.vscode/settings.json):

{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": "explicit"
  }
}

pre-commit ด้วย lint-staged + husky:

npm install --save-dev husky lint-staged
npx husky init
// package.json
{
  "lint-staged": {
    "*.{ts,tsx}": ["eslint --fix", "prettier --write"]
  }
}
# .husky/pre-commit
npx lint-staged

CI

- run: npm ci
- run: npm run typecheck    # tsc --noEmit
- run: npm run lint         # eslint
- run: npm run format:check # prettier --check
- run: npm test

3 ชั้นแยกกัน: tsc (type), eslint (บั๊ก/pattern), prettier (รูปแบบ)

เรื่องที่คนมักพลาด

  • ไม่เปิด type-aware rules — พลาด no-floating-promises, no-unsafe-* ที่จับบั๊กจริง
  • type-aware rules ช้าใน editor — projectService: true (แทน project) เร็วขึ้นเยอะใน typescript-eslint ใหม่
  • ESLint จัดรูปแบบ + Prettier ชนกัน — ใช้ eslint-config-prettier (config เก่า) หรือ config ใหม่ที่ไม่มี formatting rule
  • eslint --fix แล้วโค้ดพัง — auto-fix ของบาง rule ไม่ปลอดภัย; review diff
  • ลืมว่า tsc ≠ eslint — eslint ไม่ทำ type check ทั้งหมด; ต้องมี tsc --noEmit ใน CI ด้วย
  • no-explicit-any: error ในโค้ดที่ migrate — เริ่ม warn แล้วค่อยไต่
  • ไม่มี pre-commit / CI check — lint config ที่ไม่ enforce = ไม่มีประโยชน์

สรุป

  • แยกหน้าที่: ESLint = บั๊ก/pattern, Prettier = รูปแบบ, tsc = type
  • typescript-eslint flat config + recommendedTypeChecked + projectService: true
  • type-aware rules ที่มีค่า: no-floating-promises, no-misused-promises, no-unsafe-*, switch-exhaustiveness-check
  • เพิ่ม: consistent-type-imports, prefer-nullish-coalescing, no-non-null-assertion (warn)
  • Prettier — .prettierrc.json, eslint-config-prettier (ถ้ามี rule ชน)
  • editor format-on-save + lint-staged/husky pre-commit + CI 3 ชั้น (typecheck/lint/format:check)

บทถัดไปว่าด้วย TypeScript กับ Node.js — @types/node, typing process.env ด้วย zod, fs/path และ ESM ใน Node