Fine-tune ESLint rules to write better TypeScript
Writing clean code is a lot easier with the right tools well configured. (And helps the AI helps you)
ESLint is a static analyzer for JavaScript programs. So, what does that mean, and what can it do for my TypeScript code?
First, by static, you don’t need to run or even compile a program to parse it. To Analyze means that it checks your code searching for flaws or poor metrics that can cause problems in the long run.
ESLint is a linter that runs before the compiler, who runs before your automated tests, which should run before the end-user. It is your first line of defense and should be as integrated with your editor as possible.
For details about integrating ESLint and VSCode, you can read my article to configure basic extensions
But ESLint would not be so popular if it was not extensible and configurable. And there is the real power and complexity. In this article, I’ll walk you through the main settings and values I use to write better TypeScript.
Oh, I forgot to mention. Sure, JavaScript was the first target language for ESLint. But as a full demonstration of its inherent versatility, it can work with several parsers. And, of course, there is a TypeScript parser you can install.
🎒 Prerequisites
To complete this tutorial, you will need the following:
- VSCode installed and configured. See my advanced guide for pro tips.
- An extension to run ESLint on the editor. Once again, this article have you covered
0️⃣ Sharpen your tools
Have a local copy of the tools on every project and keep it updated. It’s easy to install ESLint, but remember to install all the parsers, extensions, and plugins.
# the main tool
npm i -D eslint
# plugin and parser for typescript
npm i -D @typescript-eslint/eslint-plugin @typescript-eslint/parser
# prettier interaction
npm i -D eslint-config-prettier eslint-plugin-prettier
After finishing, add them to the eslint.json
configuration file.
Bonus: See the default rules on eslint recommendations
{
"parser": "@typescript-eslint/parser",
"extends": [
"eslint:recommended",
"plugin:prettier/recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended"
],
"plugins": ["prettier", "@typescript-eslint"],
"env": {
"browser": true,
"es6": true,
"node": true
},
"globals": {},
"rules": {}
}
Now you are good to go and write your own rules.
1️⃣ Write simple instructions
Think about you as a writer and your code as your prose. If you want to be understood, start with simple sentences. While writing programs, sentences increase complexity with the kind and the number of operators you use.
Reduce the use of ternaries and avoid dividing complex expressions into simple steps.
{
"max-statements-per-line": ["warn", { "max": 1 }],
"no-nested-ternary": "warn",
"no-unneeded-ternary": "warn",
"one-var-declaration-per-line": ["warn", "always"],
"operator-assignment": ["warn", "always"],
"operator-linebreak": ["warn", "none"]
}
2️⃣ Write plain and small functions
Following the simile of the writer, the sentences are grouped into paragraphs. And paragraphs into chapters. The former are equivalents to our blocks (conditional or repetitive), and the latter to functions or methods (something with a name).
Reduce the size of functions, and reduce their inputs. And above all, don’t nest blocks within blocks within blocks…
{
"max-depth": ["warn", 1],
"max-lines-per-function": [
"warn",
{ "max": 10, "skipBlankLines": true, "skipComments": true }
],
"max-nested-callbacks": ["warn", 1],
"max-params": ["warn", 2]
}
3️⃣ Take control of your logic
The plot of a novel is the reason you read it. Same for your business logic; that’s why the code is written. The inherent complexity is unavoidable, but we must strive to spread it out and express it clearly. The last thing we want is to add unnecessary complexity.
Reduce the size of your classes by sharing responsibilities. Make it crystal clear what choices the code can take. And distribute these paths in such a way that anyone can follow them without getting lost.
{
"complexity": ["warn", { "max": 5 }],
"max-lines": ["warn", 100],
"no-else-return": "warn"
}
4️⃣ Add meaning and conventions to your naming
A style guide is a standard tool used by magazines and publishing agencies. And so should it be between software teams.
Use the same casing across the code base and name things to express intention.
{
"no-magic-numbers": [
"warn",
{
"detectObjects": false,
"enforceConst": true,
"ignore": [-1, 0, 1, 2, 10, 100],
"ignoreArrayIndexes": true
}
],
"@typescript-eslint/naming-convention": [
"warn",
{
"selector": "default",
"format": ["camelCase"],
"leadingUnderscore": "forbid"
},
{
"selector": "typeLike",
"format": ["PascalCase"]
},
{
"selector": "typeParameter",
"format": ["PascalCase"],
"prefix": ["T", "K"]
},
{
"selector": "enumMember",
"format": ["UPPER_CASE"]
},
{
"selector": ["memberLike", "variableLike"],
"types": ["boolean"],
"format": ["PascalCase"],
"prefix": ["can", "did", "has", "is", "must", "needs", "should", "will"]
}
]
}
5️⃣ Use what is needed, nothing more.
Lastly, pay attention to things the compiler doesn’t care about. Take care of word space and optional syntax expressions.
A consistent code base is a reader’s best friend. Keep it concise and keep it clear.
{
"arrow-parens": ["warn", "as-needed"],
"block-spacing": ["warn", "always"],
"curly": ["warn", "all"],
"no-multiple-empty-lines": ["warn", { "max": 1, "maxEOF": 1 }],
"no-unused-vars": "off",
"@typescript-eslint/explicit-member-accessibility": [
"warn",
{
"accessibility": "no-public",
"overrides": {
"parameterProperties": "explicit"
}
}
],
"@typescript-eslint/explicit-function-return-type": "warn",
"@typescript-eslint/no-unused-vars": "warn",
"@typescript-eslint/no-useless-constructor": "warn",
"@typescript-eslint/no-empty-function": "warn"
}
🧰 To take away
ESLint settings file
Following is a gist
with the JSON
settings you need to configure ESLint to write better TypeScript.
Feel free to leave comments or share your own settings.
🤖 AI code generators
Code generation AI tools can help you create code faster and better using natural language input or code completion suggestions. They can save time, cost, and effort for developers and users alike.
Following a style guide can help AI code generation tools produce consistent, readable, secure, and efficient code.
Some AI code generation tools may offer features to customize or improve the style of the code.
🌅 Conclusion
Help yourself and spread good practices across your team by enforcing ESLint rules. And make sure to help your new helpers by adjusting classical tools to work with those intelligent ones.
There are a lot of defaults and recommended pre-configurations. But to smash it, apply these rules and see how your code base shines. ✨
learn, code, enjoy, repeat
Alberto Basalo