Typescript with eslint

Marcellin Nshimiyimana
Friday Knowledge
Published in
3 min readFeb 14, 2022

This week, I learned how to write custom eslint rules

TL;DR

Eslint provides a quick and easy way to write and use custom rules!

One of 2022 year resolution is to improve my rxjs knowledge. And that led me to start replacing Promises with Observables in most of my projects.

In order to make sure all Promise occurrences are completely removed, I am going to be relying on eslint to tell me which parts of my code are using Promises.

However, since there is no prebuilt-in rule that can flag promise usages, I had to create a custom rule.

In this writeup, we will be looking at what it takes to write and use eslint custom rules.

First, let us start by providing a command to run the rule

npx eslint src/**/*.ts --rulesdir custom-eslint-rules --config .eslintrc.js

custom-eslint-rules is the folder where we are going to put the rule.

Next, we need to add the rule to .eslintrc.js

module.exports = {  parser: '@typescript-eslint/parser',  parserOptions: {    tsconfigRootDir: __dirname,    project: ['./tsconfig.json'],  },  "rules": {    "observable-no-promise": ["error"]  }
};

Here we include @typescript-eslint/parser because we are linting typescript files.

Now, let us write the rule. For the sake of time, we will write a simpler version, which only targets function declaration.

The logic goes like this: if a function returns a promise, then report it, so that it can be converted to returning an observable.

observable-no-promise-mini.ts

ReturnStatement is the token that eslint uses to identify all return statements, you can find a list of all available tokens here.

So, for a piece of code like below, you will get a linting error.

But after converting the function to returning an Observable, the linting error goes away!

Conclusion

With its friendly rule-creation process, eslint allows developers to enforce best practices no matter how ad-hoc those best practices are.

Bonus — using custom rules inside Angular apps

If you use angular cli, then you would have to register these custom rules inside angular.json file, like shown below

Resources

--

--

Marcellin Nshimiyimana
Friday Knowledge

Always debugging, because problem knowledge equals half the solution!