What steps should I take to resolve the eslint issue indicating that a TypeScript props interface is not being utilized, even though it is being used?

One of my components utilizes AvatarProps for its props:

Below is the interface declaration for AvatarProps:

export interface AvatarProps {
  userName: string;
  userLastName: string;
  userImg?: string;
  onPress?: Function;
  backgroundColorAvatar?: string;
  editMode?: boolean;
  onPressEdit?: Function;
  editButtonIcon?: string;
  backgroundColorEditButton?: string;
  textStyle?: TextStyle;
}

Upon linting with eslint, an error message appears:

5:15  error    'AvatarProps' is defined but never used  

This eslint check is triggered during commit using lefthook from a lefthook.yml file configured as follows:

 pre-commit:
  parallel: true
  commands:
    lint:
      files: git diff --name-only @{push}
      glob: "*.{js,ts,jsx,tsx}"
      run: npx eslint {files}
    types:
      files: git diff --name-only @{push}
      glob: "*.{js,ts, jsx, tsx}"
      run: npx tsc --noEmit
commit-msg:
  parallel: true
  commands:
    commitlint:
      run: npx commitlint --edit

How can I resolve this error in a clean manner?

Answer №1

Have you considered updating your component to this structure?

import React from 'react'
import type { AvatarProps, DimensionsType } from '../shared/types';

const Avatar: (props: AvatarProps) => JSX.Element = ({
        userName,
        userLastName,
        userImg,
        onPress,
        backgroundColorAvatar,
        editMode,
        onPressEdit,
        editButtonIcon,
        backgroundColorEditButton,
        textStyle,
    }) => {
        return <>
           {/* Your component goes here */}
        </>;
    };

This method provides a clearer and more descriptive way of defining the types for a functional component. Using

(props: AvatarProps) => JSX.Element
allows you to include all standard props along with any additional fields specified in AvatarProps. This enables you to incorporate child components as shown below:

import React from 'react';
import { Text } from 'react-native';

export interface AvatarProps {
    userName: string;
    userLastName: string;
}

const MyChildrenComponent = () => {
    return <></>;
};

const Avatar: (props: AvatarProps) => JSX.Element = ({ userName, userLastName, children }) => {
    return (
        <>
            {children}
            <Text>{userName + ' ' + userLastName}</Text>
            {/* Include the remaining component implementation here */}
        </>
    );
};

const SomeParentComponent = () => {
    return (
        <Avatar userName="Something" userLastName="">
            <MyChildrenComponent />
        </Avatar>
    );
};

While this approach has its drawbacks, such as not explicitly typing the function arguments (props) and the implicit nature of the children argument, it offers a structured way to define functional components. For more details, refer tothis article.

UPDATE: It's worth noting that React.FC is not necessary. You can define your component without using it like so:

const Avatar: (props: AvatarProps) => JSX.Element = ({
    userName,
    userLastName,
    userImg,
    onPress,
    backgroundColorAvatar,
    editMode,
    onPressEdit,
    editButtonIcon,
    backgroundColorEditButton,
    textStyle,
}) => {
    return <>{/* Your component implementation */}</>;
};

In this example, JSX.Element represents the return type of the component, but there are other options available for specifying the return type of a functional component.

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

There is no overload that fits the current call | Typescript, React, and Material UI

Embarking on my TypeScript journey with React and Material UI, I am hitting a roadblock with my initial component. // material import { Box } from '@material-ui/core'; // ---------------------------------------------------------------------- ...

The 'disabled' property is not found in the 'MatButton' type, however, it is necessary in the 'CanDisable' type

Issue found in node_modules/@angular/material/core/option/optgroup.d.ts: Line 17: Class '_MatOptgroupBase' does not correctly implement interface 'CanDisable'. The property 'disabled' is missing in type '_MatOptgroupBas ...

Just starting out with React and encountering the error: Invalid element type, a string was expected

I seem to be going in circles with the following issue as I try to load the basics of a React app into the browser. An error message stating 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite c ...

Converting an array of objects into a dictionary using TypeScript

I'm attempting to convert an array of objects into a dictionary using TypeScript. Below is the code I have written: let data = [ {id: 1, country: 'Germany', population: 83623528}, {id: 2, country: 'Austria', population: 897555 ...

Looking to retrieve a single data point from [object][object]

Presented here is an angular component: import { Component, OnInit } from '@angular/core'; import { Hall } from 'src/app/models/hall.model'; import { HallService } from 'src/app/services/hall.service'; import { ActivatedRoute, ...

Unlocking keys of JavaScript class prior to class initialization

My constructor was becoming too large and difficult to maintain, so I came up with a solution to start refactoring it. However, even this new approach seemed bulky and prone to errors. constructor(data: Partial<BusinessConfiguration>) { if(!d ...

How to efficiently display nested object data using Angular Keyvalue pipe

I am facing an issue with a particular HTTP request that returns an observable object containing multiple properties. One of these properties is the 'weight' object which has two key values, imperial and metric. While attempting to loop through ...

Tips for stopping TypeScript code blocks from being compiled by the Angular AOT Webpack plugin

Is there a way to exclude specific code from Angular's AOT compiler? For instance, the webpack-strip-block loader can be utilized to eliminate code between comments during production. export class SomeComponent implements OnInit { ngOnInit() { ...

Utilizing External Libraries Added Through <script> Tags in React

My goal is to develop a Facebook Instant HTML5 application in React. Following their Quick Start guide, Facebook requires the installation of their SDK using a script tag: <script src="https://connect.facebook.net/en_US/fbinstant.6.3.js"></scrip ...

The search for d.ts declaration files in the project by 'typeRoots' fails

// Within tsconfig.json under "compilerOptions" "typeRoots": ["./@types", "./node_modules/@types"], // Define custom types for Express Request in {projectRoot}/@types/express/index.d.ts declare global { namespace Express { interface Request { ...

What sets npm install -g react-native-cli apart from utilizing npx react-native init <project name>?

**Can you explain the difference between setting up react-native-cli with npm install -g react-native-cli and init as opposed to using npx react-native init? As I was developing a React Native app, I encountered some strange errors. Initially, I set up m ...

What is the best way to run tests on this method using Jest?

import { format, getDaysInMonth, getMonth, getYear, isValid, parse } from "date-fns"; export class DateService { public getDaysInMonth(month?: Date) { return getDaysInMonth(month || new Date()); } What is the best way to test this func ...

Providing properties to the main Vue.js components

An Issue I'm Facing I am currently attempting to pass a prop to my root constructor. To achieve this, I have been exploring the use of propsData, which I learned about from this resource: var appComponent = Vue.component('app', require(&ap ...

Error: There was a problem trying to import the `.d.ts` file

Software Stack Vue version 3.2.19 @vue/test-utils version 2.0.0-rc.15 Typescript version 4.1.6 Issue Description Encountering an error when running the command vue-cli-service test:unit --no-cache. Please refer to the TypeError screenshot (link to Con ...

The rendering of the Angular 2 D3 tree is not functioning properly

Attempting to transition a tree created with d3 (v3) in vanilla JavaScript into an Angular2 component has been challenging for me. The issue lies in displaying it correctly within the component. Below is the code snippet from tree.component.ts: import { ...

The datatype 'string' cannot be assigned to the datatype '(token: string) => void'

Within my Angular2 application, I have a class that includes several properties which will be assigned values within components. @Injectable() export class Globals { private token: string; private authorization: string; private roleUser: boole ...

Navigating the maze of Material UI in React with TypeScript

I have a functioning code, but I am trying to incorporate Material UI into it. However, when I replace 'input' with 'TextField', I encounter the following error: Uncaught (in promise) Error: Request failed with status code 422 at cr ...

Using React with Typescript: Passing Props and Defining Data Types

As a relatively new TypeScript enthusiast, I find myself facing some challenges. Specifically, I am struggling with errors in my code and uncertain about how to properly pass props and select the correct type. Any guidance on this matter would be greatly a ...

Ways to invoke the function in a separate component

How can I use ViewChild to call a method in a different component? I have a method in the piechart component that I want to access from the app component using ViewChild. In my piechart.component.ts file: export class PiechartComponent { constructor() ...

What is the best way to add query parameters to router.push without cluttering the URL?

In my current project, I am using NextJS 13 with TypeScript but not utilizing the app router. I am facing an issue while trying to pass data over router.push to a dynamically routed page in Next.js without compromising the clarity of the URL. router.push({ ...