The TypeScript error reads: "An element is implicitly assigned the 'any' type because an expression of type 'any' cannot be used to index a specific type."

[Hey there!][1]

Encountering this TypeScript error message: { "Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ 0: { image: string; title: string; text: string; }; 1: { image: string; title: string; text: string; }; 2: { image: string; title: string; text: string; }; }'.",}. TS7053

Curious about where I should include my interfaces or maybe if they are needed at all?

this part is emphasized setCurrent(carouselData[event.target.getAttribute("data-Testimonials")])

trying to figure out how to update them. It's puzzling, considering I'm still new to coding with just a month of experience.

My Code for managing carousel::

interface CarouselCardProperties {
   image: string;
   title: string;
   text: string;
}

export default function Testimonials() {
   const carouselData = {
       0: {
           image: tobi,
           title: "I no longer have to howl at the moon to call for my lady !!",
           text: "Tobi ~ Vancouver, Canada",

       },
       1: {
           image: girly,
           title: "With Enrico going on dates, we have more time to ourselves!",
           text: " Gina ~ Rome, Italy",

       },
       2: {
           image: loveshades,
           title: "I no longer have to worry about staying clean, I kitties licking me every night.  I have Love Shades on.",
           text: " Princess ~ Georgia, USA",
       },
   };

   const [current, setCurrent] = useState(carouselData[0])

   const [active, setActive] = useState(0)

   const handleSetClick = (event:any) => {

       setCurrent(carouselData[event.target.getAttribute("data-Testimonials")])
       setActive(event.target.getAttribute("data-Testimonials"))

   };
   return (
       <Container>
           <Img src={current.image} />
           <Title>{current.title}</Title>
           <Text>{current.text}</Text>
           <div>
               {Object.keys(carouselData).map(index => (
                   <Span
                       onClick={(event:any) => handleSetClick(event)}
                       data-Testimonials={index}
                       key={index} />
               ))}
           </div>
       </Container>
   )
}


 [1]: https://i.stack.imgur.com/A9CwZ.png

Answer №1

What is the purpose of using the data-Testimonials attribute?

You can simplify by passing the index directly to handleSetClick:

const handleSetClick = (index: keyof typeof carouselData) => {
    setCurrent(carouselData[index])
    setActive(index)
};

return (
   <Container>
       <Img src={current.image} />
       <Title>{current.title}</Title>
       <Text>{current.text}</Text>
       <div>
           {Object.keys(carouselData).map(index => (
               <Span
                   onClick={() => handleSetClick(index)}
                   key={index} />
           ))}
       </div>
   </Container>
)

Answer №2

The following code snippet

const carouselData = {
    0: {
        // ...
    }
}

initializes the carouselData object with numerical indices. However, you are accessing it using

event.target.getAttribute("data-Testimonials")
, which can have any type.

To ensure type consistency, it is recommended to strongly type your event parameter so that

event.target.getAttribute("data-Testimonials")
returns a string type. It is then advised to redefine carouselData with string indices like this:

const carouselData = {
    '0': {
         // ...
     },
    '1': {
         // ...
     }
}

Avoiding the use of any type whenever possible is generally preferred in order to prevent such problems.

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

Retrieving the value of a submit button within the `onSubmit` event handler in a React application

In my usual process, I typically handle the form submission by utilizing the onSubmit handler. <form onSubmit={e => { ... } }> <input ... /> <input ... /> <button type="submit">Save</button> </form> ...

"Exploring the power of Angular's translation capabilities paired with

I'm currently working on translating a multistep form using Angular Translate and routing with ui-router. Everything seems to be functioning properly except for one issue. Below is the snippet of my code: Translation Setup: .config(function ($t ...

Adding an icon to the Autocomplete TextField in MUI v5 in Reactjs: A step-by-step guide

I created an autocomplete feature with the code below and attempted to display an icon after selecting each item, but unfortunately, it didn't work as expected! import { useState } from 'react' import { TextField,InputAdornment ,Autocomplete ...

Using Promise.all within an async function to handle variables inside of Lambda functions

I've spent the past couple of days trying to find a solution to this issue. I've simplified my code to mostly pseudo code for ease of understanding. What I'm struggling with is creating an async function that acts as a trigger for an SQS qu ...

"Disabling a FormControl within a FormArray in Angular 4: A Step-by-

I've come up with a code snippet below that I thought would disable the FormControl in a FormArray. some.component.html <form [formGroup]="testForm"> <div *ngFor="let num of countArr"> <input type="text" formNameArray="arr ...

Naming axes in Chart.js is a simple process that can easily be implemented

Greetings to all, I'm currently working on creating bar charts using chartjs...everything is going smoothly except for one thing - I am struggling to find a clean way to name my axes without resorting to CSS tricks like absolute positioning. Take a ...

What is the process for creating an xpath for hyperlinks with the 'contains text' attribute?

I am in need of creating Xpath for links based on contained text. I have devised the following code to achieve this, however, a scenario arises when there are three links named 'Entity', 'Entity Type', and 'Entity Group'. If I ...

Reduce the dimensions of a CSS attribute automatically

Displayed below is the image with a width of 192 and height of 109: <a href="https://www.blogger.com/u/1/blogger.g?blogID=4402911157743442948#"><img alt="" class="thumbnail" height="109" src="https://2.bp.blogspot.com/-E5ftfbCCgkw/XjnLpO347cI/AAA ...

Weird Chrome behaviors with CSS3 animations

I have been working on a CSS3 animation that involves rotating a div with an image in the background. My goal is to have the same animation play at a different speed when the user hovers over the element. Here is the code snippet I have been using: .roc ...

Utilizing Isotope JS on your Wordpress website

I'm in the process of integrating the .js plugin, Isotope, into my Wordpress installation. It should be positioned at the bottom of this page: To achieve this, I am referring to an example on codepen: https://codepen.io/desandro/pen/mEinp The script ...

Is it possible to continuously increase the value of a CSS property with each click?

I am trying to implement a feature where the value of an element decreases each time a different element is clicked. Currently, I have the following code: $("#trigger_heritage").click(function () { $(".heritage_content ul").css("margin-left", + -880); ...

Updating dropdown menu selection after successful form submission validation

I'm currently working on a PHP sign up/registration form that retains and resubmits user input if validation fails. Although I have successfully implemented text boxes, password inputs, and radio buttons, I am encountering some challenges with the dro ...

Tips for effectively making REST requests from a ReactJS + Redux application?

I'm currently working on a project using ReactJS and Redux, incorporating Express and Webpack as well. I have successfully set up an API and now need to figure out how to perform CRUD operations (GET, POST, PUT, DELETE) from the client-side. Could so ...

What is the best way to bring a nested object to the top level without deleting the original top level

Imagine having the following dataset: data = [{ "_id" : "2fApaxgiPx38kpDLA", "profile" : { "name" : "Karina 1", "avatar" : "avatar1.jpg", "bio" ...

Tips and tricks for seamlessly aligning a specific section of your webpage to ensure it scrolls smoothly into view

My codes are not being centered when I use smooth scrolling on a specific section of a Bootstrap carousel template. Is there an easier way to achieve this? The explanation in a post from six years ago didn't help much. Here are my codes and screenshot ...

Utilizing the power of dynamic variable naming within ng-repeat

Has anyone ever tried using a similar approach? I am having trouble parsing {{}} within an ng-repeat. It works fine with ng-options. <option value="" ng-repeat="k in selected_grp_keys_{{value.key.id}}" value="{{k.id}}" ng-selected="k.id == value.fk_k ...

What could be causing the issue with ng-show in Angular?

When a user clicks on an icon, I want to display a drop-down menu. I attempted to use the ng-show directive for this purpose, but unfortunately, the drop-down menu is not appearing. I created an icon ..., and when clicked, I attempted to open the drop-do ...

Error in React-Native: Unable to locate main project file during the build process

Just integrated cocoapods into a React Native project. After a successful build, RN is throwing this error... https://i.stack.imgur.com/czn2W.png No errors in Xcode during the build process, but Xcode is displaying these warnings https://i.stack.imgur.c ...

Creating a Sticky Header and Footer with Responsive Design: Ensuring Content Div Expansion between Them

Greetings. I am working on creating a simple responsive HTML layout as described below: HTML: <div id="header"></div> <div id="content"></div> <div id="footer"></div> CSS: #header{ wi ...

Having issues with Exit Property functionality in Framer Motion when using react js

Help Needed: Framer Motion Exit Property Not Working I've been trying to get the exit motion to work on Framer Motion with React JS for over a week now, but everything else seems to be functioning correctly. I have installed the latest version of Fra ...