Tips on getting ESLint with a flat configuration to adhere to rules found in tsconfig (specifically useDefineForClassFields)

I want ESLint to behave in the same way as the rules check in my tsconfig.json file.

Here is the code snippet:

export class SomePage  {
  private page: Page;
  commentButton = this.page.getByTestId('open-comments');

  constructor(private page: Page) {}
};

This is how my tsconfig.json looks like:

{
    "compilerOptions": {
      "target": "ESNext",
      "useDefineForClassFields": true,
      "module": "CommonJS",
      "sourceMap": true,
      "baseUrl": "."
    }
}

The line where commentButton is declared is highlighted because of an error:

Property 'page' is used before its initialization.ts(2729)

Visual Studio Code has detected this issue, but ESLint seems to have missed it. Here is my eslint.config.mjs configuration:

import pluginJs from '@eslint/js';
import globals from 'globals';
import tseslint from 'typescript-eslint';

export default [
  { files: ['**/*.ts'] },
  {
    languageOptions: {
      globals: globals.node,
    },
  },
  pluginJs.configs.recommended,
  ...tseslint.configs.recommended,
];

Given that this rule is part of ES2022, why is ESLint not respecting it?

Would importing the tsconfig into ESLint config make sense?

Environment:

$ npx tsc -v
 Version 5.6.3

package.json

{
  "name": "tests",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "lint": "npx eslint . -c ./tslint.config.mjs --max-warnings=0"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@eslint/js": "^9.12.0",
    "@types/node": "^22.7.5",
    "eslint": "^9.12.0",
    "globals": "^15.11.0",
    "typescript-eslint": "^8.8.1"
  }
}

Answer №1

What's happening is that instead of allowing TypeScript to check things, you are only using linting with specified rules that can be enforced during linting but not through transpilation.

If you want full code checking and not just linting, you will need to utilize tslinter and provide parser options for proper parsing:

export default tseslint.config(
    ...tseslint.configs.recommended,
    pluginJs.configs.recommended,
    {
        languageOptions: {
            globals: globals.node,
            parserOptions: {
                projectService: true,
                project: "./tsconfig.json",
                tsconfigRootDir: import.meta.url,
            },
        },
    }
);

In your tsconfig.json, include the following:

{
// Other configs you have
    "files": ["./eslint.config.mjs"]
}

Results:

  4:23  error  'page' is defined but never used  no-unused-vars
  4:29  error  'Page' is not defined             no-undef

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

specialized registration process with auth0 in Angular

I am attempting to enhance the user information in a single call. The process involves first signing up with a username and password on Auth0, followed by adding additional userinfo to the database during the callback phase. However, I am encountering diff ...

Bidirectional Data Binding with Angular 2 Services

Wondering about the connection between salary.service and player.component in Angular 2. If the salary variable is updated in the service, will it automatically reflect in the view of the player component? Initially, the player.component view displays a s ...

Having difficulty in accessing the node modules

As a C#/C++ programmer new to nodejs, I am looking to incorporate typescript into my code. However, when attempting to import modules like fs or stream, I am encountering the following error: Module not found Interestingly, VisualStudio 2017 is able to ...

An error occurred with the datepicker: Unable to connect to 'bsValue' as it is not recognized as a property of 'input'

Despite importing DatepickerModule.forRoot() in my Angular unit test, I am encountering the following error: Error: Template parse errors: Can't bind to 'bsConfig' since it isn't a known property of 'input'. (" ...

Concealing the value of 'Zero' in an input field with TypeScript and Angular 2

<input type="text" class="form-control" id="transactionAmount" maxlength="10" HideZero="true" [(ngModel)]="userBalance.transactionAmount" ...

Create a one-of-a-kind Angular 6 material table component featuring unique custom columns

My goal is to streamline the process of creating custom material tables by using a specialized table component that allows me to quickly generate unique tables for different data sources with built-in pagination and sorting. All I need to provide are the d ...

What is the method for developing a Typescript-connected High-Order React Component with Redux?

I am looking to develop a React Higher-Order Component that can safeguard routes within my application from unauthorized users without an access token. I aim to use this HOC to wrap a Component like so in the parent component: <Route exact path ...

Issue with Angular Ionic HTTP promise functionality not performing as expected

My service retrieves data from an endpoint : Service.ts getAllProducts(){ return new Promise( (resolve, reject) => { this.apiService.get( this.allProducts, `/products`, {} ) .then( data => resolve( data.map( item => this.par ...

Displaying data from Java backend to Angular front-end using HTTP

I'm in the process of developing an application that utilizes an Angular frontend and Java backend. I am looking to showcase data from the backend, which is stored in JSON format. How can I achieve this? Initially, I created a JSON array in my Java c ...

Error: Missing provider for MatBottomSheetRef

While experimenting in this StackBlitz, I encountered the following error message (even though the MatBottomSheetModule is imported): ERROR Error: StaticInjectorError(AppModule)[CountryCodeSelectComponent -> MatBottomSheetRef]: S ...

Caution: Refs cannot be used with function components, even when using forwardRef() with Styled Components

I am currently encountering a warning message that says Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?. The confusing part is that I am already using forwardRef() and it see ...

Ways to conceal a component based on a specific condition?

In my Angular 8 application, I need to dynamically hide a component based on a specific condition. The condition I want to check is: "status === EcheqSubmissionStatus.EXPIRED" Initially, I attempted the following approach: EcheqProcessComponent templat ...

Tips on utilising the datepicker solely with the calendar icon, avoiding the need for any input fields

I'm currently working on a Datatable filter and I would like to incorporate a calendar icon to facilitate date filtering by simply clicking on the Datatable Header. At this stage, I've managed to display a calendar Icon on my Datatable header, b ...

Tips for modifying the width of the mat-header-cell in Angular

Is there a way to customize the mat-header-cell in Angular? I've been trying to change its width without success. Any suggestions would be greatly appreciated. <ng-container cdkColumnDef="name"> <mat-header-cell *cdkHeaderCellDe ...

Is there a way to reset the selected value of a specific option in Mat-Select?

Using mat-select, I need to reset the selection for a specific value of mat-select's mat-option. For instance, take a look at this example on StackBlitz In the example, the mat-select has three options; when selecting Canada, it should revert back t ...

Angular 11 now includes the ability to implement lazy loading for modules

Here is the configuration of my app-routing.module.ts: const routes: Routes = [ { path: 'login', component: LoginComponent }, { path: '', canActivate: [AuthGuard], component: HomeComponent, children ...

What is the most effective method to clean an object in JavaScript while maintaining security?

To circumvent the JavaScript delete operator (source: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/delete), I have opted to utilize object destructuring to eliminate private properties: //sample helper-function in ts const sani ...

The attribute 'constructor' is not found on the 'T' type

I'm currently working on a project using Next.js and TypeScript. I've come across an issue where TypeScript is giving me the error "Property 'constructor' does not exist on type 'T'" in my generic recursive function. Here&apo ...

An issue has occurred: TransformError SyntaxError: Unexpected keyword 'const' was encountered

While practicing programming with React-Native, I encountered a problem that I couldn't figure out how to solve. I attempted to use solutions from various forums, but none of them worked. import { StyleSheet, Text, View, Image } from 'react-nativ ...

The module './App.vue' or its corresponding type declarations could not be located

I am currently in the process of building a Vue 3 application using the Primevue theme along with Vite, Typescript, and Pinia. After setting up the project using CMD, I encountered an issue with the main.ts file. It is throwing an error that states: `impo ...