Sub topic 13
Writing your own rules
This chapter shows how to write a custom typescript-eslint rule, test it, and load it into a flat config. Most projects never need one. By the end you should be able to judge when a custom rule is worth the cost.
You should already be comfortable with the flat config from earlier chapters, the difference between syntactic and type-checked rules, and the project service setup. Examples use ESLint 9 and typescript-eslint 8.
When a custom rule is the right tool
Custom rules cost you a test suite, upgrade work when the AST or APIs change, and documentation for the team. Try cheaper options first.
| Need | Cheapest option |
|---|---|
| Ban a global, import, or property | `no-restricted-globals`, `no-restricted-imports`, `no-restricted-properties` |
| Ban a code shape that an AST selector can describe | `no-restricted-syntax` with a selector |
| Ban a pattern that depends on types | Custom rule |
| Enforce a project convention with options, autofixes, or suggestions | Custom rule |
The no-restricted-syntax rule accepts CSS-like AST selectors and a message. It handles many team conventions without any plugin code:
// an entry in the flat config array
{
files: ['src/**/*.ts'],
rules: {
'no-restricted-syntax': [
'error',
{
selector:
"CallExpression[callee.property.name='forEach'] > ArrowFunctionExpression[async=true]",
message: 'forEach ignores the promises returned by async callbacks.',
},
],
},
},A selector sees only syntax. It cannot tell whether items is an array or a custom class with its own forEach method. When you need that distinction, write a rule.
How a rule runs
A rule is an object with metadata and a create function. ESLint calls create once per file. create returns an object of listeners keyed by AST node type, and ESLint calls each listener as it walks the tree.
The parser produces the AST and, when type information is configured, a set of parser services. These give the rule access to the TypeScript program and its type checker. This is the same mechanism that type-checked built-in rules use.
Writing a type-aware rule
The rule below reports forEach calls with an async callback, but only when the receiver is an array. A forEach call does not wait for the promises its callback returns, so errors are lost and work finishes in an unpredictable order.
Install the utilities first:
npm install --save-dev @typescript-eslint/utils @typescript-eslint/rule-tester vitestThen create the rule:
// tools/eslint-rules/no-async-foreach.ts
import { AST_NODE_TYPES, ESLintUtils } from '@typescript-eslint/utils';
const createRule = ESLintUtils.RuleCreator(
(name) => `https://example.com/lint-rules/${name}`,
);
export const noAsyncForEach = createRule({
name: 'no-async-foreach',
meta: {
type: 'problem',
docs: {
description: 'Disallow async callbacks passed to Array#forEach.',
},
messages: {
asyncForEach:
'forEach does not wait for async callbacks. Use a for...of loop, or Promise.all with map.',
},
schema: [],
},
defaultOptions: [],
create(context) {
const services = ESLintUtils.getParserServices(context);
return {
CallExpression(node) {
const callee = node.callee;
if (
callee.type !== AST_NODE_TYPES.MemberExpression ||
callee.computed ||
callee.property.type !== AST_NODE_TYPES.Identifier ||
callee.property.name !== 'forEach'
) {
return;
}
const callback = node.arguments[0];
if (
callback === undefined ||
(callback.type !== AST_NODE_TYPES.ArrowFunctionExpression &&
callback.type !== AST_NODE_TYPES.FunctionExpression) ||
!callback.async
) {
return;
}
const receiverType = services.getTypeAtLocation(callee.object);
const typeName = receiverType.getSymbol()?.getName();
if (typeName === 'Array' || typeName === 'ReadonlyArray') {
context.report({ node: callback, messageId: 'asyncForEach' });
}
},
};
},
});The parts that matter:
ESLintUtils.RuleCreatortakes a function that builds the documentation URL from the rule name. It returns a typedcreateRulehelper, socontextand the node types are inferred.meta.messagesholds message templates. You report bymessageId, which keeps text out of the logic and lets tests assert on the ID.schemadescribes the rule's options as JSON Schema. Use[]when the rule takes none. ESLint rejects a config that passes options to a rule whose schema forbids them.- Early returns narrow the node. The
AST_NODE_TYPESenum turns thetypestring into a discriminated union, socallee.property.nameis only reachable after the checks. getParserServicesthrows a clear error if the file was parsed without type information. That makes the rule fail loudly in a misconfigured project instead of silently reporting nothing.
If your rule doesn't need types, don't call getParserServices. It then runs in any setup and doesn't add to the type-aware performance cost from the earlier chapter.
Options, fixes, and suggestions
Add an option by changing schema and defaultOptions, then reading the second argument of create: create(context, [options]). The type of options comes from the defaultOptions tuple, so declare the type with the createRule<Options, MessageIds> generics.
To offer an automatic fix, set fixable: 'code' in meta and pass fix(fixer) { ... } to context.report. If a change could alter behavior, make it a suggestion instead. Set hasSuggestions: true and pass suggest: [{ messageId, fix }]. An editor then offers the change as a choice and eslint --fix skips it.
Testing the rule
RuleTester from @typescript-eslint/rule-tester runs your rule against snippets. Each invalid case lists the errors you expect, so a test fails if the rule stops reporting or reports the wrong thing.
// tools/eslint-rules/no-async-foreach.test.ts
import { RuleTester } from '@typescript-eslint/rule-tester';
import { afterAll, describe, it } from 'vitest';
import { noAsyncForEach } from './no-async-foreach';
RuleTester.afterAll = afterAll;
RuleTester.describe = describe;
RuleTester.it = it;
RuleTester.itOnly = it.only;
const ruleTester = new RuleTester({
languageOptions: {
parserOptions: {
projectService: { allowDefaultProject: ['*.ts*'] },
tsconfigRootDir: import.meta.dirname,
},
},
});
ruleTester.run('no-async-foreach', noAsyncForEach, {
valid: [
`[1, 2].forEach((n) => console.log(n));`,
`
const items = [1, 2];
for (const n of items) {
await Promise.resolve(n);
}
`,
`
class Bag {
forEach(fn: (n: number) => Promise<void>): void {}
}
new Bag().forEach(async (n) => {});
`,
],
invalid: [
{
code: `[1, 2].forEach(async (n) => { await Promise.resolve(n); });`,
errors: [{ messageId: 'asyncForEach' }],
},
],
});Run it with npx vitest run.
The third valid case is why this rule needs types. Without type information, the custom Bag class would be reported as a false positive. Always include cases like this. Rules fail most often by reporting things they shouldn't.
The allowDefaultProject option lets the tester parse inline snippets without listing each one in a tsconfig.json. It can't resolve imports between snippets. If a test needs multiple files, give the tester real fixture files and a tsconfig.
Loading the rule into your config
A flat config plugin is a plain object with a rules map. Define it inline and register it under a namespace of your choice:
// eslint.config.ts
import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';
import { defineConfig } from 'eslint/config';
import { noAsyncForEach } from './tools/eslint-rules/no-async-foreach';
const localPlugin = {
rules: { 'no-async-foreach': noAsyncForEach },
};
export default defineConfig(
eslint.configs.recommended,
tseslint.configs.recommendedTypeChecked,
{
languageOptions: {
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
},
{
files: ['src/**/*.ts'],
plugins: { local: localPlugin },
rules: { 'local/no-async-foreach': 'error' },
},
);The rule is now local/no-async-foreach, and everything from earlier chapters applies to it: severity, file scoping, inline directives, and the editor integration.
Edge cases and failure modes
- Union and generic receivers.
getTypeAtLocationreturns the type as written. A receiver typedT extends unknown[]orstring[] | undefinedhas a different symbol thanArray. Decide whether to handle these. The@typescript-eslint/type-utilspackage has helpers for this, and the built-in rules show how to use them. - Parenthesized and optional calls.
items?.forEach(...)wraps the call in aChainExpression. TheCallExpressionlistener still sees the inner call, but some shapes need a second listener. Write a test for each shape you care about. - Rules that depend on the file. Reading
context.filenamelets a rule behave differently by path, butfilesscoping in the config is usually cleaner. - Performance. A listener runs for every matching node in every file. Return early on cheap syntactic checks before calling into the type checker, as the rule above does.
- Version drift. Custom rules depend on the AST shape and on
@typescript-eslint/utils. Keep it on the same major version astypescript-eslintand run the rule tests whenever you upgrade.
Exercise
A teammate wants to ban any call to parseInt that omits the radix argument. Would you write a custom rule, and what would you reach for first?
Show answer
Start with no-restricted-syntax and a selector such as CallExpression[callee.name='parseInt'][arguments.length=1] plus a message. The check depends only on syntax, with no type information, so a selector is enough. Write a custom rule only if you later need options, autofixes, or checks that depend on types.
Exercise
In the no-async-foreach test file, why is the Bag class case listed under valid, and which line of the rule makes it pass?
Show answer
Bag has its own forEach method, so an async callback is not a bug there. The rule looks up the receiver's type with services.getTypeAtLocation and reports only when the symbol name is Array or ReadonlyArray. The Bag receiver fails that check, so no report is made.