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

I am experiencing difficulties in initializing a class (controller) in Nextjs version 13

I am working on an application built with Next.js where I have a controller class responsible for handling all the access functions, such as retrieving data from the database. However, I keep encountering this error message: Error [ReferenceError]: Cannot ...

Creating a Duplicate of the Parent Element and its Child Elements using jQuery

Here is a code snippet I have that adds a new paragraph when a button is clicked. Currently, the script clones the "sub" div and appends it to the "main" div. However, the issue is that it only copies the content of the "inner" div within the "sub" div ins ...

Is it possible to incorporate two ng-repeat directives within a single td element in a table?

The results so far Expected outcome Please advise me on how to incorporate two ng-repeats within one td. When I use a span tag afterwards, the expected result is not achieved. I have used one ng-repeat in the td and the other in a span tag, which is why t ...

ridiculing callback within parameter

I have a model setup in the following way: export class MyClass { grpcClient: MyGRPCClient; constructor(config: MyGRPCClientConfig) { this.grpcClient = new MyGRPCClient( config.serverUrl, grpc.credentials.createInsecure(), ); ...

Ensure that all asynchronous code within the class constructor finishes executing before any class methods are invoked

Looking to create a class that takes a filename as a parameter in the constructor, loads the file using XmlHttpRequest, and stores the result in a class variable. The problem arises with the asynchronous nature of request.onreadystatechange, causing the ge ...

What is the best way to create a background image that remains hidden behind content as you scroll through a webpage?

I am looking to recreate the effect seen on the background image of this website , where the image gets covered by content as you scroll down. ...

Customize back button functionality in Ionic 2

Is it possible to modify the behavior of the back button shown in this image? I would like to specify a custom destination or perform an action before navigating back, instead of simply returning to the previous page. https://i.stack.imgur.com/EI2Xi.png ...

What impact does the order of the element I'm specifying in my .css file have on its appearance after being rendered?

(An update has been added below) In my project, I am working with a .css file and an index.html document. The goal is to create a panel of buttons on the screen [to prototype the usability of a touchscreen interface], with each button assigned a specific ...

Automatically updating quantity with the power of jQuery

I have created a spreadsheet where users can input their expenses and the total will update automatically. Initially, I have set some default numbers in my HTML which are editable for users to modify as needed. However, I am facing an issue with my JQuer ...

Creating a visual feast: A guide to crafting a stunning image gallery

Is there a way to ensure all the pictures in a table are the same size, orientation, and inline? Currently, my images vary in size and rotation. The CSS I have applied is styling only the first image differently from the rest. Any help is appreciated! CSS ...

Is there a way to ensure that the navigation tabs in Tailwind always display a scroll bar?

My navigation bar contains multiple tabs that require scrolling to be fully visible. On the initial load, users may not realize they can scroll to see additional tabs. To address this issue, I want to always display a scrollbar on the navigation bar. ...

Is it possible to iterate through HTML form data using JSON arrays or objects?

I've been searching this website and the internet for a while now, trying to figure out how to save multiple arrays to my localStorage. I asked a question earlier which helped me progress a bit, but I'm still struggling to grasp the concept. I c ...

Is there anyone who can provide a comprehensive explanation for what is going on here?

{ // Let's figure out how to launch my HTML file as a webpage in Chrome. "version": "0.2.0", "configurations": [ { "type": "pwa-chrome", &q ...

What is the process for incorporating a collection in Mongoose?

Trying to clear the Users collection before and after tests: before(function(done) { mongoose.connection.collections['users'].drop(function(err) { mongoose.connection.collections['users'].insert(user, done); }); }); after(func ...

The Material-UI datepicker seems to be malfunctioning

I've come across an issue with the material-UI date picker not functioning correctly. I am using material-UI and Reactjs, but unfortunately, it's not working as expected. Can someone please assist me in resolving this problem? const minDate ...

Challenge with scroll function in Internet Explorer JavaScript

Here is the code snippet I am working with: var lastScrollTop = 0; window.addEventListener("scroll", function(){ var st = window.pageYOffset || document.documentElement.scrollTop; if (st > lastScrollTop){ $('.sticky').addClass('insi ...

Sending user input from search component to main App.js in React

I'm currently working on an app that searches a Movies database API. I have a main fetch function in App.js, and in tutorials, people are using a search bar within this main APP component. I'm wondering if it would be better to create a separate ...

Error: Module not found '!raw-loader!@types/lodash/common/array.d.ts' or its type declarations are missing

I encountered a typescript error while building my NEXT JS application. The error message was: Type error: Cannot find module '!raw-loader!@types/lodash/common/array.d.ts' Below is the content of my tsConfig.json file: { "compilerOptions& ...

Can anyone provide guidance on how to trigger an HTTP 500 error in my React.js and Next.js applications?

To ensure that our custom error page is displayed instead of the default HTTP 500 error following a recent security vulnerability, I am looking to purposely simulate the error. While we have special processing in place for 404 and 403 errors on our site, ...

CSS for mobile devices not loading until the device is rotated

My website, redkrypt.com, is functioning perfectly on my laptop. However, I am facing an issue where the css file will only load on my iPhone 4S after I rotate it once. Once I do this, the website works both vertically and horizontally. I have tried variou ...