Error in Typescript: An element is implicitly assigned the 'any' type because a string expression is being used to index a different type

Hello everyone, I'm fairly new to TypeScript and I've been struggling to troubleshoot an error in my code. Can someone please assist me with solving this TypeScript error?

I keep getting the error message: "Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ 'sections.hero': ({ sectionData, key }: props) => Element; }'. No index signature with a parameter of type 'string' was found on type '{ 'sections.hero': ({ sectionData, key }: props) => Element; }'."

Here is my code :

type sectionDataProps = {
  sectionData: {
    __component: string;
  };
};

// Map Strapi sections to section components
const sectionComponents = {
  'sections.hero': Hero,
};

// Display a section individually
const Section = ({ sectionData }: sectionDataProps) => {
  // Prepare the component
  const SectionComponent = sectionComponents[sectionData.__component];

  if (!SectionComponent) {
    return null;
  }

  // Display the section
  return <SectionComponent data={sectionData} />;
};

// Display the list of sections
const Sections = (props: { sections: [] }) => {
  return (
    <>
      {/* Show the actual sections */}
      {props.sections.map((section) => (
        <Section
          sectionData={section}
          key={`${section.__component}${section.id}`}
        />
      ))}
    </>
  );
};

export default Sections;

Answer №1

In TypeScript, you cannot access properties that may not exist. This means that if you have a type like { a: number }, you can only access the a property. Trying to access the b property would result in a type error because it doesn't exist.


For example, consider having this type for the key:

__component: string;

And this type for the object where the key is expected to be on:

const sectionComponents = {
  'sections.hero': Hero,
};

This implies that only one specific string value is allowed for this operation:

sectionComponents[sectionData.__component]

The only valid string in this case is 'sections.hero', any other string will not be permitted.

To address this issue, there are a few ways to fix it.


One solution is to change the type of the __component property to:

type sectionDataProps = {
  sectionData: {
    __component: keyof typeof sectionComponents;
  };
};

With this modification, any generic string value is no longer acceptable. The strings must now be keys of the sectionComponents object.

The rest of your code should work without requiring further modifications. Playground Link


If you prefer not to modify the props types, you need to adjust the logic of your function to ensure that you avoid accessing non-existent properties.

// Display sections individually
const Section = ({ sectionData }: sectionDataProps) => {
  // Prepare the component
  if (sectionData.__component in sectionComponents) {
      const key = sectionData.__component as keyof typeof sectionComponents
      const SectionComponent = sectionComponents[key];
      return <SectionComponent data={sectionData} />;
  }

  return null
};

Here, we use an in check to confirm the existence of a property in the object before proceeding. By explicitly casting it to keyof typeof sectionComponents, we inform TypeScript that this operation is safe.

Playground Link

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

Retrieve the raw text from the input field instead of the date object

Below is the HTML code for an input field: <div class="input-group input-group-md"> <input id="date" name="date" [readOnly]="disabled" type="text" placeholder="M0/d0/0000 Hh:m0:s0" [placeholder]="pl ...

The occurrence of TypeError in next.js Dropzone stating that (0 , _mantine_core__WEBPACK_IMPORTED_MODULE_0__.rem) is not a function is indicating

I am encountering an issue while trying to render a dropzone component using Next.js and Mantine. For reference, I am following the documentation at . Here is the import statement: import dropzone I am receiving an error message that says: I have inclu ...

Generics causing mismatch in data types

I decided to create a Discord bot using DiscordJS and TypeScript. To simplify the process of adding components to Discord messages, I developed an abstract class called componentprototype. Here is how it looks (Please note that Generators are subclasses li ...

Tips for enabling the TypeScript compiler to locate bokeh's "*.d.ts" files

I recently made the switch from Bokeh's convenient inline extension framework to their npm based out of line build system. I'm currently working on getting my extension to build, but I've noticed that Bokeh organizes all TypeScript *.ts.d fi ...

"Angular application experiencing navigation blockage due to multiple concurrent HTTP requests using RxJS - Implementation of priority-based cancel queue

I've come across similar threads, but I have yet to find a suitable solution for my specific issue. Situation: Currently, I'm navigating on both the server side and client side simultaneously. This entails that every frontend navigation using ro ...

Instantiate an object of the ng.IQService type without using injection

Is it possible to define a local variable in the controller of type ng.IQService ( private _q: ng.IQService;) without requiring injection? My technology stack includes typescript and angular. The reason for this requirement is due to existing legacy code ...

Yarn dev in Next.js didn't show the updated server changes

I've been working on a custom nextjs server file, but no matter what changes I make, they don't seem to show up in the terminal after building and running the code. Here's an example snippet from my file: const app: any = next({ ...

Is there a way to automatically incorporate a component into every view within a Next.js application?

Is there a more efficient and less cumbersome way to import components for every view in a Next.js app? I am interested in incorporating the "arwes" framework into my project and utilizing components from . One of the examples of a component I will be usin ...

Is there a way for me to receive the status code response from my backend server?

My component makes a call to a servlet, which then sends a POST HTTP request to the backend (using Spring Boot). I want the backend to return the status of the POST request that was sent earlier. This is my code: res= this.CS.postcompetenze(this.comp) Th ...

Blank webpage caused by ngx TranslateService

Every time I attempt to translate Angular components using ngx-translate/core by utilizing the translateService in the constructor, the page appears blank. This is my appModule : import { NgModule } from '@angular/core'; import { BrowserModule } ...

Angular 9: The instantiation of cyclic dependencies is not allowed

After transitioning from Angular 8 to Angular 9, I encountered an issue with a previously functioning HTTP communication service. The error message now reads: Error: Cannot instantiate cyclic dependency! HttpService at throwCyclicDependencyError (core ...

Issue with Next.js 14's "Route interception" feature not functioning correctly when deployed in a production environment

Summary The "Intercepting routes" feature is functional locally (localhost:3000) However, the same feature does not work in production (website.com) Watch this video to see the issue The Issue I'm facing a problem with implementing a feature wher ...

Guide to retrieving Azure web app application settings in a TypeScript file

I recently created an Angular 2 application using Visual Studio 2015. After that, I successfully published my Angular 2 web app to Azure Web App and everything seems to be working fine. However, I am facing a challenge in accessing the application setting ...

Tips for implementing a custom hook in the submission function of a React hook form

Currently, I'm tackling the issue with the next 13 tasks using the react hook form. One custom hook has been developed inside the hook folder named src/hooks/use-api.ts for handling global API functionalities like useGet, usePost, and more. The probl ...

Missing Directory Issue Upon Deploying Node.js App on Google App Engine

I have a Node.js web application built using TypeScript and Koa.js that I am looking to deploy on Google App Engine. The code has already been transpiled into JavaScript and is stored locally in the ./dist/src/ directory. Essentially, I only need to depl ...

using spread operator to extract properties from API response objects

Currently undergoing a React/Next course, we recently had to retrieve data from an API that returns a list of objects containing information to populate the page. This task was accomplished using Next's getStaticProps method, passing the data to the ...

Guide on retrieving POST data in sveltekit

Hello, I'm new to sveltekit and I am trying to fetch post data in sveltekit using a POST request. Currently, I am utilizing axios to send the post data. const request = await axios .post("/api/user", { username, email, ...

What is the process for integrating unit tests from external sources into an Angular project following an upgrade to version 15

As of Angular v15, the require.context function has been removed from the test.ts configuration file. I used to rely on require.context to expose tests outside of the Angular project to Karma. Now that it's no longer available: const contextGlobal = ...

I find that the Next.js useEffect function hinders my ability to smoothly navigate to a

I have a page displaying all the cards. When I click on a specific card, it redirects me to that card's details. The id is included in the URL. http://localhost:3000/cards/card?id=6539ccd487fa315543646ce5 I extract this id and retrieve the correspond ...

Tips for storing the device token received from Firebase Cloud Messaging in an Ionic2 application

Using the FCM plugin for ionic2, I was able to successfully implement push notifications. For reference, you can check out the plugin here. I followed the steps outlined in this Github repository, and everything is working smoothly so far. Now, my next go ...