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:

https://i.sstatic.net/cZBl1.png

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

Is there a method to create a typecheck for hasOwnProperty?

Given a certain interface interface Bar { bar?: string } Is there a way to make the hasOwnProperty method check the property against the defined interface? const b: Bar = { bar: 'b' } b.hasOwnProperty('bar') // works as expected b. ...

Create an interface object in TypeScript with no initial properties

I'm currently developing an app with angular 5 (TS) and I've encountered a problem while trying to initialize an empty object of my interface. The solution that I found and attempted is as follows: article: Article = {} as Article; However, ...

The error message "mongoose.connect is not a valid function" has been encountered while

While working on my passport sessions and integrating JWTs, I encountered some confusing errors when trying to run my application: ERROR TypeError: mongoose.connect is not a function. (In 'mongoose.connect(config.MongoURL, { useNewUrlParser: true ...

Determining the height of a component in React Native

https://i.sstatic.net/VLqIb.jpg The image demonstrates the styling of the component: <TouchableOpacity style={{ height: listDataSource[item.key].isExpanded ? 500 : 140, width: widthw * 0.8, marginHorizontal: 12, backgroundColor: 'red', }} Wh ...

Need an EventEmitter that works with both Node.js and React-Native

I am encountering an issue where I am using an npm package that needs the events module in this manner: var EE = require('events').EventEmitter; The problem arises when working with React Native, as it cannot locate the events module. Is there ...

Encountering difficulties with loading external textures in react-three/drei/native

I've encountered an issue while trying to load an image texture using useTexture and apply it to a meshStandardMaterial in my react-native app. Interestingly, the texturing works perfectly fine when I import the image from the local assets folder. How ...

Unable to establish connection between React Native Socket.IO and a Node.js server

As I work on developing a React Native Expo app that requires real-time communication using socket.io, my Node.js server is up and running on localhost. Here's the code snippet: In React Native - home.js import { io } from "socket.io-client" ...

Is there a way for me to input only the value and have TypeScript automatically determine the key of an object?

My challenge lies in having an object with string keys, but I do not want them to remain as strings. Instead, I desire the keys to be the exact values of the object. This means that I must input the value of the object accordingly to meet certain criteria. ...

When utilizing TS Union Types from an Array, the resulting type will consistently be a

After reading this response, I decided to create some union types from a string[] in order to return a list of valid type values. However, instead of that, the type ends up accepting any string value. const arrayDays = Array.from(Array(32).keys(), (num) =& ...

Modify typescript prior to typechecking

Consider the following TypeScript file: class A { private x? = 0; private y? = 0; f() { console.log(this.x, this.y); delete this.x; } } const a = new A(); a.f(); When building it in webpack using awesome-typescript-loader ...

What are the steps to styling a component with CSS Emotion?

I am facing an issue with using a theme with TypeScript in this component const buttonDisabled = css` color: ${({ theme }) => theme.color}; `; Is there a way to correctly type this component? Error: No overload matches this call. Overload 1 of 2, & ...

Deciding between bundling a Typescript package and using tsc: When is each approach the best choice

When it comes to publishing a Typescript NPM package (library, not client), I have two main options: 1. Leveraging Typescript's compiler First option is to use the Typescript compiler: tsc and configure a tsconfig.json file with an outDir setting: { ...

I am experiencing issues with my HTML select list not functioning properly when utilizing a POST service

When using Angularjs to automatically populate a list with *ngFor and then implementing a POST service, the list stops functioning properly and only displays the default option. <select id="descripSel" (change)="selectDescrip()" > <option >S ...

Encountering Issues with NextJS Dynamic SSR: Mobile Devices stuck on loading screen

Issue: The dynamic import feature of Next JS is encountering loading issues specifically on mobile browsers such as Google Chrome and Safari on IOS. Strangely, the functionality works smoothly on desktop browsers like Google Chrome and Mozilla. The projec ...

Issue with TypeScript not detecting exported Firebase Cloud Functions

Dealing With Firebase Cloud Functions Organization I am managing a large number of Firebase Cloud Functions, and in order to keep the code well-structured, I have divided them into separate files for each function category (such as userFunctions, adminFun ...

Creating a project using TypeScript, NodeJs, and mongoose-paginate-v2 seems like an impossible

Having trouble setting up mongoose-paginate-v2 in my current project. I'm facing three errors while trying to compile my code. Any ideas on why this is happening? Many thanks. node_modules/@types/mongoose-paginate-v2/index.d.ts:34:21 - error TS2304: ...

Is there a way to check if a date of birth is valid using Regular Expression (RegExp) within a react form?

const dateRegex = new RegExp('/^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.] (19|20)\d\d+$/') if (!formData.dob || !dateRegex.test(formData.dob)) { formErrors.dob = "date of birth is required" ...

What is the method for comparing fields within an input type in type graphql with the assistance of class validator decorators?

I am working with the following example input type: @InputType() class ExampleInputType { @Field(() => Number) @IsInt() fromAge: number @Field(() => Number) @IsInt() toAge: number } Can I validate and compare the toAge and fromAge fields in th ...

Adding a backslash in Angular: Tips and Tricks

I have a question about adding a backslash to a string that is returned from a div, for example Car1 \sold. Although I am able to retrieve the status, I am having trouble adding the backslash. Here is what I have tried so far: <span>{{addBackl ...

Guidance on installing only TypeScript dependencies for building from package.json using npm, ensuring a leaner build without unnecessary 150MB of additional dependencies

Is there a way to optimize the dependency installation process for building, minimizing unnecessary packages and reducing the total download size by avoiding 150MB of excess files? This is more of a query rather than an immediate requirement Current depe ...