ESLint in TypeScript is giving a false alarm: "Function has been defined but not used."

Having a unique function called iwAddClassAndRemoveInSiblings within the lib\iw-browser.ts file:

"use strict";

/* This function adds a specified CSS class to a given element and removes this class from its siblings.
   Equivalent to jQuery: $(element1).addClass(CSSClass).siblings().removeClass(CSSClass) */
function iwAddClassAndRemoveInSiblings(element: Element, CSSClass: string): void {
  for (const sibling of element.parentNode.children)
    sibling.classList.remove(CSSClass)
  element.classList.add(CSSClass)
}

The utilization of this function is found in the lib\iw-carousel\iw-carousel.ts file:

document.addEventListener('click', (event) => {
  const target = <HTMLElement>event.target
  if (target.matches('.iw-carousel__indicators li'))
    iwCarouselShowSlide(target.closest('.iw-carousel'), Number(target.dataset.slideTo))
})

/* Aiding in showing the i-th slide of an iw-carousel. */
const iwCarouselShowSlide = (carousel: HTMLElement, slideIndex: number) => {
  const slides = carousel.querySelectorAll('.iw-carousel__item')
  iwAddClassAndRemoveInSiblings(slides[slideIndex], 'active')
}

References to the compiled iw-browser.js and iw-carousel.js can be located in the iw-carousel.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  <script src="lib/iw-carousel/iw-carousel.js"></script>
  <script src="lib/iw-browser.js"></script>
</head>
<body>
   <!-- irrelevant html content -->
</body>
</html>

An issue arises with Typescript ESLint falsely flagging the iwAddClassAndRemoveInSiblings function as unused, despite functioning correctly within Visual Studio Code and when executed through the command line:

'iwAddClassAndRemoveInSiblings' is defined but never used. eslint(@typescript-eslint/no-unused-vars)

This matter seems specific to ESLint, as Visual Studio Code validates the function's usage appropriately.

A correct configuration may be necessary for ESLint or TypeScript. The installation procedures for TypeScript and ESLint are outlined at: How to use ESLint TypeScript Airbnb configuration?

Below are the TypeScript and ESLint configuration files:

.eslintrc.js:

module.exports = {
  root: true,
  parser: '@typescript-eslint/parser', // enables understanding of TypeScript syntax by ESLint
  parserOptions: {
    project: ['./tsconfig.json'],      // essential for "type-aware linting"
  },
  plugins: [
    '@typescript-eslint',              // allows usage of rules within the codebase
  ],
  extends: [
    'airbnb-typescript/base',          //utilize Airbnb config
  ],
  rules: { }
};

tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2016",
    "module": "commonjs",
    "sourceMap": true
  }
}

package.json:

{
  "name": "iw-components",
  "version": "0.1.0",
  "description": "...",
  "main": "index.js",
  "directories": {
    "lib": "lib"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/iwis/iw-components.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/iwis/iw-components/issues"
  },
  "homepage": "https://github.com/iwis/iw-components#readme",
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^2.34.0",
    "@typescript-eslint/parser": "^2.34.0",
    "eslint": "^6.8.0",
    "eslint-config-airbnb-typescript": "^7.2.1",
    "eslint-config-standard-with-typescript": "^16.0.0",
    "eslint-plugin-import": "^2.20.2",
    "eslint-plugin-node": "^11.1.0",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-standard": "^4.0.1",
    "typescript": "~3.7.5"
  }
}

Answer №1

The issue at hand is that ESLint is unaware of the global function. You have a couple of options to address this:

  1. Avoid using globals — they have historically been a source of numerous bugs. Opt for modules instead. Alternatively,
  2. Inform ESLint that the function is global.

There are two components to option #2: In the file where the function is declared, you must notify ESLint that the function is not "unused," and in the file where you utilize it, ESLint needs to be informed about it.

Refer to the documentation for more information, but essentially:

  • To indicate to ESLint that a function is not unused, use a comment as outlined here, for example:

    /* exported iwAddClassAndRemoveInSiblings */
    
  • To declare to ESLint that it exists (in another file), employ a comment as specified here, such as:

    /* global iwAddClassAndRemoveInSiblings */
    

However, I strongly advise utilizing modules instead.

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

How can parameters be implemented in Angular similar to NodeJs Express style?

Is there a way to implement a Parameter in Angular routes that resembles the NodeJs style? I have a route like **http://myhost.domain.com/signin**" and I want to pass an id for the signin request. Although I can achieve this using **http://myhost.doma ...

What is the best way to retrieve a class property within an arrow function that is passed to a constructor?

On a React login page, I created a class for rendering authentication methods. The class includes a default render function that I need to customize. class AuthMethod { constructor(initializer: Pick<AuthMethod, 'id'> & Partial<A ...

Problem with Ionic 2 checkboxes in segment controls

I encountered an issue with my screen layout. https://i.sstatic.net/bFeZN.png The problem arises when I select checkboxes from the first segment (Man Segment) and move to the second segment (Woman Segment) to choose other checkboxes. Upon returning to th ...

Error in AngularFire2 typings: The property 'take' is not present in the type 'FirebaseObjectObservable<any>'

Recently, I upgraded my ionic app from beta 11 to rc0, which also involved transitioning from typescript 1.8 to version 2. After following the configuration steps for AngularFire2 on the site Getting Started with Ionic 2 RC0, Firebase 3 + AngularFire 2, I ...

I am experiencing difficulties with my data not reaching the function in my component.ts file within Angular

My current project involves integrating Google Firebase to handle the login functionality. I encountered an issue where the data inputted from the HTML page to the component.ts file was not being processed or reaching Firebase. However, when I initialized ...

Implementing subclass properties in TypeScript that override parent class properties

I have a base class called Parent from a library with certain properties, and a derived class Child which inherits the same properties but with different data types. class Parent { propertyA: string; propertyB: string; propertyC: string; const ...

Sending a POST request with parameters using HttpClient

My current challenge involves making a POST request to an endpoint that requires query string parameters instead of passing them in the body of the request. const params = new HttpParams() .set('param1', '1') .set('param2' ...

Error: Attempting to access an undefined property ('call') on Next.js is causing a TypeError

Exploring the realms of Next.js and Typescript for a new project! My goal is to utilize next.js with typescript and tailwind CSS by simply entering this command: npx create-next-app -e with-tailwindcss my-project Smooth sailing until I hit a snag trying t ...

Error: Swiper dependency was not located in the Typescript and Ionic-Vue project

Looking to switch from ion-slides to swiper due to limitations with dynamic rendering. After correctly adding <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e0d09170e1b0c3e49504e504f">[email protected]</a> in th ...

Updating the function type definition in TypeScript after importing it into a separate file

I have created a unique hook named useDropdownSelection. It's a straightforward one. Take a look at the code below: import { useState } from 'react' export const useDropdownSelection = (initialValue: string) => { const [selectedOption, ...

What could be causing the issue of CSS Styles not being applied to an Angular 2 component with Vaadin elements?

Currently, I am immersed in the tutorial on Vaadin elements using Angular 2 that I stumbled upon here In section 5.3, Styles are applied to the app.component.ts as shown below import { Component } from [email protected]/core'; @Component({ select ...

"Dealing with cross-origin resource sharing issue in a Node.js project using TypeScript with Apollo server

I am encountering issues with CORS in my application. Could it be a misconfiguration on my server side? I am attempting to create a user in my PostgreSQL database through the frontend. I have set up a tsx component that serves as a form. However, when I tr ...

Warning: Node encountering unexpected Unhandled Promise Rejection ERROR

I've encountered a problem in my code that is triggering an UnhandledPromiseRejectionWarning in Node, but I'm struggling to understand the root cause. Here's a simplified version of the code: export class Hello { async good(): Promise<s ...

Verify optional chaining support in Angular app for browsers

Within my Angular application, I am looking to verify if a client's browser supports optional chaining (es2020) in order to load a library that contains both a modern ES version and a legacy one. The issue arises when the Angular compiler (which I su ...

Function in Typescript that accepts either a single object or an array of objects

We frequently use a simple function declaration where the function can accept either a single object or an array of objects of a certain type. The basic declaration looks like this: interface ISomeInterface { name: string; } class SomeClass { pu ...

Angular is unable to start the variable_INITIALIZation process

I've created a method called get that returns data of type ProductModel. getProduct(id:number): Observable<ProductModel[]> { const url = `${'api/product/getProductById/'}/${id}`; return this.http.get<ProductModel[]>(u ...

How can I access a TypeScript variable from a global var set in a .cshtml file?

I have defined several variables in my .cshtml file to be used in my angular services: <script> var _APIURL = '@(Url.Content("~/Admin/api/"))'; var _AREAURL = '@(Url.Content("~/Admin/"))'; var _APPURL = &a ...

Combining portions of objects in Angular2

I want to combine two identical type observables in Angular2 and return an observable of the same type in a function. My goal is to: transform this setup: obs1.subscribe(obs => console.log(obs)) (where I receive): { count: 10, array: <some ...

Detecting and removing any duplicate entries in an array, then continually updating and storing the modified array in localstorage using JavaScript

I'm facing an issue with the function I have for pushing data into an array and saving it in local storage. The problem is that the function adds the data to the array/local storage even if the same profileID already exists. I want a solution that che ...

Refine the category based on a specified key

Currently, I am in the process of developing a React Hook using TypeScript. In this hook, I am passing both a key and a value that will be associated with this key as arguments. My objective is to constrain the type of the value based on the specified key. ...