Sub topic 13
Writing Your Own typescript-eslint Rules
Assume that you know TypeScript syntax, npm, ES modules, and the basic flat configuration format. A custom rule is a small program that inspects parsed source code and reports patterns your project wants to prevent or encourage.
When a custom rule is the right tool
Use an existing rule when one already expresses the policy. Write a custom rule when the policy depends on your domain, such as requiring a project logger, rejecting a deprecated API, or enforcing a convention in generated client code.
A custom rule usually has these parts:
| Part | Purpose |
|---|---|
| Metadata | Describes the rule and its messages |
| Visitor | Receives selected syntax-tree nodes |
| Condition | Decides whether the node violates the policy |
| Report or fix | Shows the problem and optionally changes the code |
ESLint parses a TypeScript file into an abstract syntax tree, or AST. The AST represents calls, functions, imports, and other source constructs as nodes. Your rule visits those nodes instead of searching raw text.
Build a rule
This rule rejects console.log calls. It uses @typescript-eslint/utils, which provides TypeScript-aware rule types and helpers.
// rules/no-console-log.ts
import { ESLintUtils } from '@typescript-eslint/utils';
const createRule = ESLintUtils.RuleCreator(
name => `https://example.com/rules/${name}`,
);
export default createRule({
name: 'no-console-log',
meta: {
type: 'suggestion',
docs: {
description: 'Disallow console.log in application code',
},
schema: [],
messages: {
avoid: 'Use the application logger instead of console.log.',
},
},
defaultOptions: [],
create(context) {
return {
CallExpression(node) {
if (
node.callee.type === 'MemberExpression' &&
!node.callee.computed &&
node.callee.object.type === 'Identifier' &&
node.callee.object.name === 'console' &&
node.callee.property.type === 'Identifier' &&
node.callee.property.name === 'log'
) {
context.report({
node,
messageId: 'avoid',
});
}
},
};
},
});The visitor receives every CallExpression. The condition narrows the node until it knows that the call is exactly console.log(...). The context.report call creates the lint diagnostic.
Register the rule as a plugin in the flat config. The typescript-eslint preset still supplies the parser and other rules.
// eslint.config.mjs
import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';
import noConsoleLog from './rules/no-console-log.js';
export default [
eslint.configs.recommended,
...tseslint.configs.recommended,
{
files: ['**/*.ts'],
plugins: {
internal: {
rules: {
'no-console-log': noConsoleLog,
},
},
},
rules: {
'internal/no-console-log': 'error',
},
},
];Run ESLint normally:
npx eslint srcType-aware custom rules
The rule above only needs syntax. A type-aware rule needs the TypeScript program so it can ask questions such as “What type does this expression have?” Enable the project service in the relevant config entry, as described for type-checked presets in the earlier chapter. A rule can then read parser services from the rule context.
Type-aware rules cost more because ESLint must load and analyze the project. Keep the rule narrow, and do not enable type-aware processing for files that do not need it.
Test and maintain the rule
Use RuleTester to define valid and invalid examples. Tests should cover the smallest valid case, nearby valid syntax, and the failure message. Add an autofix only when the replacement is safe and unambiguous.
Common errors include visiting the wrong AST node, forgetting computed properties such as console['log'], and reporting without a stable messageId. Keep project policy in the rule documentation and make the rule name specific enough to search.
Exercise
Why should a custom rule inspect AST nodes instead of searching the source file for the text "console.log"?
Show answer
AST inspection understands syntax, so it can distinguish a function call from a comment or string and can examine the call's structure.