Blog>
Snippets

Adopting TypeScript with ESLint

Provide a configuration example for ESLint that supports TypeScript, ensuring both JavaScript and TypeScript code are linted.
module.exports = {
  parser: '@typescript-eslint/parser', // Specifies the ESLint parser
  extends: [
    'plugin:@typescript-eslint/recommended', // Uses the recommended rules from the @typescript-eslint/eslint-plugin
    'plugin:eslint-comments/recommended',
    'prettier/@typescript-eslint', // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier
    'plugin:prettier/recommended', // Enables eslint-plugin-prettier and displays prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
  ],
  parserOptions: {
    ecmaVersion: 2020, // Allows for the parsing of modern ECMAScript features
    sourceType: 'module', // Allows for the use of imports
  },
  rules: {
    // Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs
    // e.g. "@typescript-eslint/explicit-function-return-type": "off",
  },
  env: {
    browser: true,
    node: true,
    es2020: true,
  },
  overrides: [
    {
      files: ['*.ts', '*.tsx'],
      rules: {
        // override/add rules settings specifically for TypeScript files
      }
    },
    {
      files: ['*.js'],
      rules: {
        // override/add rules settings specifically for JavaScript files
      }
    }
  ]
}
This is a sample ESLint configuration file that supports both TypeScript and JavaScript. It specifies the parser and plugins needed for TypeScript and configures the rules, environments, and parser options for ESLint. It also includes overrides to allow for specific rule customizations for different file types.
// Sample TypeScript file: example.ts

interface IExample {
  attribute: string;
}

class Example implements IExample {
  public attribute: string;

  constructor(value: string) {
    this.attribute = value;
  }

  public greet(): void {
    console.log(`Hello, ${this.attribute}!`);
  }
}

// Sample JavaScript file: example.js

function greet(name) {
  console.log('Hello, ' + name + '!');
}
These are example snippets of code written in TypeScript and JavaScript. The TypeScript code defines an interface and a class that implements it. The JavaScript code is a simple function that greets a name. Both snippets should be linted correctly by the ESLint configuration provided.