ESLint's no-unused-vars rule is triggered when Typescript object destructuring is employed

I'm encountering an issue with my Typescript code where I am destructuring an object to extract a partial object, but it's failing the linter check. Here is the problematic code snippet:

async someFunction(username: string): Promise<UserDTO> {
    const userEntity = await getUserByUsernameAsync(username);

    if (userEntity ) {
        const { password, ...result } = userEntity ;
        return result;
    }

    return null;
}

The code above removes certain parts of an object and returns the remaining data. However, when running the linter, I receive this warning:

warning  'password' is assigned a value but never used      @typescript-eslint/no-unused-vars

The issue lies in assigning password to a variable that is not being utilized. How can I rectify this problem to satisfy the linter?

Answer №1

To prevent verification for additional siblings, you have the option to include

"@typescript-eslint/no-unused-vars": ["error", { "ignoreRestSiblings": true }]
in your set of rules within eslintrc.js.

For instance:

module.exports = {
  root: true,
  parser: "@typescript-eslint/parser",
  plugins: [
    "@typescript-eslint",
  ],
  extends: [
    "plugin:@typescript-eslint/eslint-recommended",
    "plugin:@typescript-eslint/recommended"
  ],
  rules: {
    "@typescript-eslint/no-unused-vars": ["error", { "ignoreRestSiblings": true }]
  },
  settings: {
    react: {
      version: "detect"
    }
  }
};

If needed, you can simply disable the linting rule entirely for that line by incorporating this into the line above it:

// eslint-disable-next-line @typescript-eslint/no-unused-vars

Answer №2

These days, it's crucial to include the following two rules in your .eslintrc.json file.

The argsIgnorePattern rule allows for underscore arguments in function signatures, while the varsIgnorePattern rule permits underscores in destructuring.

We're specifically using the pattern: ^_ to ensure that variable names start with an underscore.

Example

"rules": {
  "no-unused-vars": ["error", {
    "varsIgnorePattern": "^_",
    "argsIgnorePattern": "^_"
  }]
}

Documentation

Notes

When working with "rest siblings," it is advised to use

"ignoreRestSiblings": true
, as mentioned in the original post. However, it's still recommended to adopt the underscore prefix as a clear indication. Also, bear in mind that without the rest pattern, using ignoreRestSiblings alone may not resolve issues when attempting to destructure and utilize underscore notation.

Answer №3

To address this issue, you can either choose to remove the linter setting by using the ignoreRestSiblings option or pass the complete object and then proceed to remove the specific property.

async function fetchData(username: string): Promise<UserData> {
    const user = await getUserDataByUsernameAsync(username);

    if (user) {
        const {...updatedUser} = user;
        delete updatedUser.password;
        return updatedUser;
    }
    
    return null;
}

Answer №4

Here's a quick tip:

Use object destructuring to extract specific fields from yourObject like this:
const { field1: _, field2: __, ...rest } = yourObject;

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

Is AngularJS not able to effectively manage the button type "reset"?

I currently have the following code snippet: <form name="editor"> <h2>Create/Update</h2> {{ editor.title.$error.required }} <div ng-class="{ 'has-error': editor.title.$invalid && editor.title.$dirty, &apo ...

Show/Hide a row in a table with a text input based on the selected dropdown choice using Javascript

Can someone please assist me with this issue? When I choose Business/Corporate from the dropdown menu, the table row becomes visible as expected. However, when I switch back to Residential/Consumer, the row does not hide. My goal is to only display the row ...

Update ngModel value following the PUT request response

I currently have a variable named dummy_value and I would like to update it using an input box. <p>{{dummy_value}}</p> <input [(ngModel)]="dummy_value" /> Upon making this change, the dummy_value updates instantly due to the two-way bin ...

Property undefined with all alert points filled

According to the console, I am facing an issue while trying to route to the dashboard after logging in because the surname property is undefined. However, when I check my alerts, I can see that it is filled correctly at all times. login(surName: string, pa ...

Unable to fetch local file using ajax from a local HTML page

According to Same Origin Policy, the SOP should not be applied to the file:// protocol. However, I'm having trouble with my code. I am running a testing page from my local system, and both when I try to access abc.txt in the same directory as the HTML ...

Increase the time of a Date by 10 seconds

Is there a way to increase the time of a JavaScript date object by 10 seconds? For example: var currentTime = new Date(); var currentSeconds = currentTime.getSeconds() + 10; currentTime.setSeconds(currentTime.getSeconds() + currentSeconds); ...

Aggregate the values in each position across various arrays and merge them into distinct arrays

I'm facing an issue that I can't seem to solve on my own. Imagine we have several arrays: [1,2,3] [1,2,3] [11,12,13] How do I go about extracting all the values at each index from these multiple arrays and combining them into separate arrays? T ...

Updating a value in an array in Angular using the same ID

I have an array of buildings that looks like this: const buildings = [ { id: 111, status: false, image: 'Test1' }, { id: 334, status: true, image: 'Test4' }, { id: 243, status: false, image: 'Test7' }, { id: 654, stat ...

What is the significance of [Function: bound ] in the context of node debugging?

So I was trying to debug my .js file using node debug and when I used catch(error) { It only displayed [Function: bound ] when I tried console.dir(error) What is causing this issue? How can I access the full error object? And how do I retrieve the stack ...

Unit testing controllers in AngularJS with Karma often involves setting up mock services to simulate dependencies

Currently, I am immersed in the development of a Single Page Application using AngularJS as part of my Treehouse Full Stack JavaScript TechDegree. My main focus right now is on conducting unit tests for the controllers. The challenge lies in testing contro ...

What can Cordova and express js bring to the table together?

I'm feeling pretty lost when it comes to displaying express views in a Cordova app client. It seems like the app would have to send a GET request and then the express application would render the view. But I'm unsure about how to actually make t ...

When invoking a function, jQuery may return an empty value

I am currently tweaking my jQuery script to retrieve a specific value upon page refresh in order to capture the return value. Initially, I attempted the following: var email_number = ''; // check if page refreshed or reloaded if (performance.n ...

An error message pops up when using Next.js with Sass, indicating that a suitable loader is required to handle this file type

I've been struggling to properly wire up my next.js project with SCSS, but no matter what I try, it just won't work. I double-checked my setup for compiling SCSS files, but the error message keeps popping up: /scss/style.scss 1:0 Module parse f ...

HTML5 enables users to pick their preferred font style

In my JavaScript and HTML5 course, I am working on developing a website where users can choose the background color and decide between using SANS SERIF or SANS fonts. The background color selection feature is already functioning successfully -- var inputC ...

The values stored in UI Router $stateParams can only be accessed and viewed

Currently, I am passing an id to a new state using $stateParams which works well. However, the issue arises when the user reloads the page since there won't be any values in $stateParams. To solve this problem, I decided to store the $stateParam id in ...

Adding content to a paragraph using Jquery

I have 4 sets of data associated with a click-bind event. My goal is to retrieve the value from a hidden field in each set and display it in a paragraph elsewhere on the page when the corresponding checkbox is clicked. Currently, I'm focused on gettin ...

Exception thrown by the 'upload' method of the Krajee file-input widget

I have been using the fileinput widget from Krajee at this link: However, I seem to be encountering an issue with the 'upload' method. Everything works perfectly fine when I upload files by clicking the upload button. But when I try to use the u ...

Steps for creating an npm package from the /build folder of Create React App

Hello! I am currently working on an app developed using the create-react-app boilerplate. After compiling and building it with npm run build, I now want to transform the /build folder into an npm package for easy use in other projects as a micro app. Can ...

When the fullscreen modal is opened, the initial image displayed is not the same as the one that was clicked on

Seeking assistance: I've been struggling with a problem for quite some time now and could really use some help from you guys. My issue involves an 'AngularJS' webapp that retrieves posts from an 'FB page' via 'OpenGraph' ...

Synchronization-free API and callback functions

I am in need of utilizing an asynchronous service. My current approach involves sending data to this service using PHP and CURL, as well as receiving data from a URL provided by the service. How can I effectively respond or wait for feedback from this serv ...