Sub topic 2
Tuning typescript-eslint Rules
Assume you know TypeScript syntax, use npm and Node.js, and have a tsconfig.json. ESLint rules report patterns that may cause bugs or make code harder to maintain. typescript-eslint adds rules that understand TypeScript syntax and, when enabled, its types.
Choosing severity and options
Each rule has a severity:
"off"disables the rule."warn"reports a problem but usually does not fail a lint command."error"reports a problem and normally makes linting fail.
Rules can also accept options after the severity. The exact options belong to each rule.
// eslint.config.mjs
import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';
import { defineConfig } from 'eslint/config';
export default defineConfig(
eslint.configs.recommended,
tseslint.configs.recommended,
{
files: ['**/*.ts', '**/*.tsx'],
rules: {
'@typescript-eslint/no-explicit-any': 'error',
'@typescript-eslint/consistent-type-imports': [
'warn',
{ prefer: 'type-imports' },
],
},
},
);Use "error" for rules that protect correctness. Use "warn" while introducing stricter style or during gradual adoption. Keep rule settings near the configuration entry whose files they affect.
Applying settings to different files
Flat config is an array of configuration entries. A files pattern scopes an entry. Later matching entries can change earlier settings.
export default defineConfig(
tseslint.configs.recommended,
{
files: ['**/*.test.ts'],
rules: {
'@typescript-eslint/no-explicit-any': 'off',
},
},
{
files: ['**/*.js', '**/*.mjs'],
extends: [tseslint.configs.disableTypeChecked],
},
);This example permits any in tests and disables type-checked rules for JavaScript files. Make exceptions narrow and document why they exist.
Turning on type-aware linting
Type-aware linting uses the TypeScript project to inspect types. It catches issues that syntax-only linting cannot, such as an unhandled promise.
import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';
import { defineConfig } from 'eslint/config';
export default defineConfig(
eslint.configs.recommended,
tseslint.configs.recommendedTypeChecked,
{
languageOptions: {
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
},
);Exercise
Which severity should you use for a rule that must block CI, and where should a test-only exception go?
Show answer
Use "error" and put the exception in a later flat-config entry scoped with a files pattern for test files.