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

Is it necessary to enforce a check for surplus properties in the return type of a function

In this particular scenario, the TypeScript compiler does not raise an error when a function returns an object with the type UserProfile even though the expected return type is UserProfileWithNoPermissions. Here's an example: interface UserProfile { ...

TypeScript is unaware that a component receives a necessary prop from a Higher Order Component (HOC)

My component export is wrapped with a higher-order component (HOC) that adds a required prop to it, but TypeScript seems unaware that this prop has already been added by the HOC. Here's the Component: import * as React from "react"; import { withTex ...

Transform the Standard class into a generic one in typescript

I've created a class that can take JSON objects and transform them into the desired class. Here's the code: import {plainToClass} from "class-transformer"; import UserDto from "../../auth/dto/user.dto"; class JsonConverter { ...

"Implementing Ionic 2 tabs allows for retrieving the previously selected option with the

Here is the code I am currently working on: onTabsChange(abc) { let selected_tab = this.tabs.getSelected(); let tab_index = selected_tab.index; console.log(tab_index); // should print current tab index but it prints previously selected tab index ...

Error TS2322: Type 'boolean' cannot be assigned to type 'undefined'. What is the best approach for dynamically assigning optional properties?

I am currently working on defining an interface named ParsedArguments to assign properties to an object, and here is what it looks like: import {Rules} from "../Rules/types/Rules"; export interface ParsedArguments { //other props //... ...

Solve the issue of the __typename union

Imagine having the following union: export type IBookmarkItemFragment = | ({ __typename: "Story" } & { story: number; }) | ({ __typename: "Product" } & { product: number; }) | ({ __typename: "Project" } & { proj ...

pm2 is launching multiple instances of identical next.js applications

I am in the process of deploying my Next.js app on my local PC. Below are the contents of my configuration and package.json files: // package.json { "name": "smarf", "private": true, "scripts": { "dev ...

Conditional generic type in return type with Typescript

How can I condition the generic return type when a value is not present? type Foo = {}; class Bar<P extends Foo> { static make<P extends Foo>(a?: P): Bar<P> { return new Bar(); } } Bar.make() // returns Bar<Foo> ...

What is the reason that Ionic Lifecycle hooks (such as ionViewWillEnter and ionViewWillLeave) do not trigger when utilized as an HTML Selector?

I have a project using Angular along with Ionic 4. I encountered an issue where the Ionic Lifecycle Hooks in the child page do not fire when it is called from the parent page's HTML using the HTML Selector. Why does this happen? How can I properly ut ...

Encountered an issue when trying to proxy to the Node.js/Express Socket.IO server with Next.js

I'm currently facing an issue with establishing a connection between my Next.js/React client and my Express/Socket.io backend (not running as a Next.js custom server). When I attempt to proxy regular HTTP requests using rewrites in the next.config.js ...

utilize console.log within the <ErrorMessage> element

Typically, this is the way the <ErrorMessage> tag from Formik is utilized: <ErrorMessage name="email" render={(msg) => ( <Text style={styles.errorText}> ...

Inefficiency in POST method prevents data transmission to MongoDB

I've developed a MERN application and now I'm testing the backend using the REST client vscode extension. This is how it looks: `POST http://localhost:4000/signup Content-Type: application/json { "email": "<a href="/cdn-cgi ...

Error: monaco has not been declared

My goal is to integrate the Microsoft Monaco editor with Angular 2. The approach I am taking involves checking for the presence of monaco before initializing it and creating an editor using monaco.editor.create(). However, despite loading the editor.main.j ...

Error: The forward function is not accessible in nextjs due to an ApolloError

Help needed with resolving the ApolloError: forward is not a function problem. I have followed the documentation and tried adding an error code, but nothing seems to be working. Please assist! apollo.client.ts import { ApolloClient, InMemoryCache } from ...

Why does my Next.js server abruptly stop after I start it up?

After creating a new app with create-next-app@latest, I encountered an issue where the server would start and then close automatically when running npm run dev. The output displayed was as follows: > <a href="/cdn-cgi/l/email-protection" class="__cf ...

Indulging in the fulfillment of my commitment within my Angular element

In my Angular service, I have a method that makes an AJAX call and returns a Promise (I am not using Observable in this case). Let's take a look at how the method is structured: @Injectable() export class InnerGridService { ... private result ...

In NextJs version 13, you can access parameters from the URL directly within the layout.js file

With the introduction of server components in Next.js 13, accessing parameters from the URL has become seamless. Let's look at an example: app/shop/[tag]/[item]/layout.js /shop/1/2 { tag: '1', item: '2' } When accessing page ...

Setting the default value for Angular Material's select component (mat-select)

Many inquiries are focused on setting a default value to display in a "Select" control. In this particular case regarding Angular 8 template driven forms, the issue lies in the inability to show the default value in the mat-select when the button is clicke ...

Using a combination of two Reducers in my redux saga store seems to be causing issues with the triggering of messages on my websocket channel. However, when using just

Implemented my store configuration using redux toolkit as shown below const rootReducer = combineReducers({ someReducer, systemsConfigs }); const store = return configureStore({ devTools: true, reducer: rootReducer , ...

Issue: The TypeError reported is due to the absence of any definition for "_co.category.category_type"

I have two models: CategoryTypes and Categories. Each category type contains multiple categories. These are my two models. Categories Model import { Categories } from '../../categories/Mode/Categories' export class CategoryType { _id: strin ...