Automatically Check TypeScript Code for Errors With ESLint
Linting with ESLint#
📝 This lesson's quiz can be found - here.
🗒️ Solutions for this lesson's quiz can be found - here.
Though VSCode includes TypeScript language support which helps recognize errors in our TypeScript code, we'll probably need more robust code checking. As an example of something we might want to forbid is preventing a variable from ever having the
any type. TypeScript won't stop us since
any is a valid basic type but as a preference, we probably don't want to have code built in our app that has the
any type since it removes the benefits of type checking.
To introduce linting into our app and take advantage of our code editor, we'll first install the VSCode ESLint extension. The VSCode ESLint extension allows us to integrate ESLint into VSCode to help provide warnings, issues, and errors in our editor.
Once the VSCode ESLint extension is installed, we'll go ahead and install a few other development dependencies that we'll need to enable ESLint configuration into our app. We'll install:
eslint: the core ESLint library
@typescript-eslint/parser: parser that will allow ESLint to lint TypeScript code
@typescript-eslint/eslint-plugin: plugin when used in conjunction with
@typescript-eslint/parsercontains many TypeScript specific ESLint rules.
server $: npm install -D eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin
We'll introduce an
.eslintrc.json configuration file in the root project directory. The
.eslintrc.json file is the configuration file that'll dictate the ESLint set up of our application. We'll look to introduce a couple of options to our ESLint configuration file.
@typescript-eslint/parser is probably the most widely used and supported parser for TypeScript code, and the one installed in our app.
The parserOptions configuration allows us to specify the language options we want ESLint to support. By default, ESLint supports ES5. We'll set the
2018 to allow us the use of modern ES features in our app.
sourceType: module to declare that we're using ES6 modules in our app.
extends option allows us to extend the rules from a certain plugin with which we've picked @typescript-eslint/recommended.