esLint - Configuring "no-unused-vars" for Typescript

Rins picture Rins · Sep 5, 2019 · Viewed 24.7k times · Source

I use esLint in all of my Typescript projects with the following settings:

  "extends": ["airbnb", "prettier", 'plugin:vue/recommended'],
  "plugins": ["prettier"],
  "parserOptions": {
  "parser": "@typescript-eslint/parser",
  "ecmaVersion": 2018,
  "sourceType": "module"
  },

+ a bunch of custom rules. I've also installed the following dependencies for Typescript support:

    "@typescript-eslint/eslint-plugin": "^1.7.0",
    "@typescript-eslint/parser": "^1.7.0",

However, one of esLint's most useful rules, https://eslint.org/docs/rules/no-unused-vars, seems to be very poorly configured for Typescript projects. For example, when I export an enum, the rule warns me that the enum isn't in use in the file where it is declared:

export enum Foo {
   Bar,
}

Similarly, when I import an interface or class to be used as a type, 'no-unused-vars' will complain again on the the line of the actual import:

In Foo.ts

export interface Foo {
   bar: string;
}

In bar.ts

import { Foo } from './Foo'
const bar: Foo = { bar: 'Hello' };

Is there any way to configure the no-unused-vars rule to take these two cases into account? I'm not a fan of disabling the rule, as it is one of the most helpful rules in my entire ruleset outside of these cases.

I've already downgraded the rule to only give a warning instead of an error, but having all my documents filled with warnings still kind of defeats the purpose of using esLint.

Filling my all my documents with //eslint-disable-line as suggested here also seems like a bad solution.

Answer

dolios picture dolios · Oct 23, 2019

It's a bit buried in the documentation, but if you add some things to the 'extends' property, you can use both the rules recommended by ESLint like no-unused-vars, and have it actually work in Typescript. Like so:

"extends": [
        "eslint:recommended",
        "plugin:@typescript-eslint/eslint-recommended",
        "plugin:@typescript-eslint/recommended"
    ],

@typescript-eslint/recommended seems to be the thing that allows eslint:recommended to deal with Typescript constructs effectively. Not sure how it would affect your other extensions though.