The Typescript error message indicates that the element is implicitly assigned the "any" type due to the index expression not being of type "number"

I am encountering an issue with a code snippet that is giving me the following error message:

Element implicitly has an 'any' type because index expression is not of type 'number'.ts(7015) 

const communes: ICommune[] = _.filter(wilayasData, (commune) => commune.wilaya_code === wilaya.wilaya_code);
      Object.keys(communes).forEach((key) => {
        communes[key].commune = communes[key].commune_name_ascii;
        communes[key].commune_ar = communes[key].commune_name;
        communes[key].daira = communes[key].daira_name_ascii;
        communes[key].daira_ar = communes[key].daira_name;
        delete communes[key].commune_name_ascii;
        delete communes[key].commune_name;
        delete communes[key].daira_name_ascii;
        delete communes[key].daira_name;
      });

The structure of the ICommune interface is as follows :

    commune_name_ascii?: string;
    commune_name?: string;
    commune_ar?: string;
    commune?: string;
    daira?: string
    daira_ar?: string
    daira_name_ascii?: string;
    daira_name?: string;
    wilaya_code?: string;
    wilaya_name_ascii?: string;
    wilaya_name?: string;

Answer №1

I made a few modifications to the interface structure as follows:

interface ICommune {
  commune_name_ascii?: string;
  commune_name?: string;
  commune_ar?: string;
  commune?: string;
  daira?: string
  daira_ar?: string
  daira_name_ascii?: string;
  daira_name?: string;
  wilaya_code?: string;
  wilaya_name_ascii?: string;
  wilaya_name?: string;
}

While implementing the code, I altered the keys to integers for better compatibility with the common index schema.

      const communes: ICommune[] = _.filter(wilayasData, (commune) => commune.wilaya_code === wilaya.wilaya_code);
      Object.keys(communes).forEach((key) => {
        const k = parseInt(key, 10);
        console.log(k);
        console.log(key);
        communes[k].commune = communes[k].commune_name_ascii;
        communes[k].commune_ar = communes[k].commune_name;
        communes[k].daira = communes[k].daira_name_ascii;
        communes[k].daira_ar = communes[k].daira_name;
        delete communes[k].commune_name_ascii;
        delete communes[k].commune_name;
        delete communes[k].daira_name_ascii;
        delete communes[k].daira_name;
      });

Alternatively, we can directly access the index instead of using the key.

        communes[index].commune = communes[index].commune_name_ascii;
        communes[index].commune_ar = communes[index].commune_name;
        communes[index].daira = communes[index].daira_name_ascii;
        communes[index].daira_ar = communes[index].daira_name;
        delete communes[index].commune_name_ascii;
        delete communes[index].commune_name;
        delete communes[index].daira_name_ascii;
        delete communes[index].daira_name;
      });

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

The parameter of type 'never' cannot be assigned with the argument of type 'number | boolean | undefined'

In my project, I am creating a validation input using TypeScript in Next.js. interface InputRules { required?: boolean min?: number max?: number minLength?: number maxLength?: number } I have defined an object that contains methods to handle val ...

Is it possible for OpenFin to store logs in a secure database and what is the process for accessing logs located at %LocalAppData%openfinapps<app>app.log

System Information Here are the details of the system setup: OpenFin Process Manager Version: RVM = 8.1.0.4 Node.js: v16.15.0 Windows 10 Angular Application with C# .NET backend Issue: The current setup saves all application logs locally on users' ...

Props that are not compatible: void cannot be assigned to ThunkAction

In my redux thunk action implemented in a container component connected to redux, I encountered an error stating that the props of App and the props passed to connect are not compatible. The issue seems to be related to expecting a function that returns a ...

Is there an array containing unique DateTime strings?

I am dealing with an Array<object> containing n objects of a specific type. { name: 'random', startDate: '2017-11-10 09:00', endDate: '2017-11-23 11:00' } My goal is to filter this array before rendering the resu ...

Show refined information upon form submission or click

I am facing a challenge with implementing filtering functionality in an input box within a form in Angular 12. Despite my efforts, I have been unable to get the pipe working correctly in the component and consequently in the view. HTML ...

What is the best way to show the stored date in the input field using the GET method in mat-datepicker?

After creating a mat-datepicker and saving the selected date in the back-end, I am now wondering how to display the saved date in the input field. Below is my code snippet: // HTML <mat-form-field appearance="fill"> <mat-label>Da ...

How to target a single TypeScript file in a React project that does not use TypeScript for compilation

I created a ReactJS application using the following command: $ npx create-react-app react-app-vanilla This app includes the following files: /.gitignore /README.md /package.json /public/favicon.ico /public/index.html /public/logo192.png /public/logo512.pn ...

Create a Jest test environment with MongoDB and TypeScript, following the guidance provided in the Jest documentation

While attempting to set up a simple test file following the jest documentation, I encountered several linter errors: https://i.sstatic.net/bAPjC.png connection: The type 'Promise<MongoClient> & void' is missing properties such as &apo ...

Angular 2 wrap-up: How to seamlessly transfer filter data from Filter Component to App Component

A filtering app has been created successfully, but there is a desire to separate the filtering functionality into its own component (filtering.component.ts) and pass the selected values back to the listing component (app.ts) using @Input and @Output functi ...

How can we effectively test arrow functions in unit tests for Angular development?

this.function = () => { -- code statements go here -- } I am looking to write jasmine unit tests in Angular for the function above. Any suggestions on how to achieve this? it("should call service",()=>{ // I want to invoke the arrow funct ...

Error: global not declared in the context of web3

I've been attempting to integrate Web3 into my Ionic v4 project for some time now. However, I keep encountering errors when I try to serve the project. Specifically, I receive an error message stating that Reference Error: global is not defined. Cre ...

The functionality to verify the presence of a child element is not functioning correctly when using

Trying to determine the existence of a child, I have created a new Firebase list observable and also attempted with an object observable. Upon creating the observable, I verify if it exists or not; however, it always returns false. Database Structure: {R ...

Adjust the input width dynamically in Angular

Looking to dynamically adjust the width of an input field and ensure that the suffix "meters (m)" sticks close to the entered number. Additionally, I want to pass a specific value to the input using `value="something"`, which then should expand the input w ...

Creating a custom string subtype in TypeScript

I am currently working on developing a game called Risk using TypeScript and React hooks. This game is played on a map, so my first step was to design a MapEditor. The state of the Map Editor is as follows: export interface IMapEditorState { mousePos: ...

Awaiting a response before triggering

Currently, I'm utilizing Serverless to build a REST get endpoint. The main goal is to request this endpoint and receive a value from the DynamoDB query (specifically from the body tag). The issue I am facing is that when this endpoint is invoked, the ...

Jasmine test confirms that momentJS objects with the same values do not match

In my angular-cli project, I have a set of Jasmine tests that include various assertions. One particular assertion looks like this: expect(dispatchSpy).toHaveBeenCalledWith({ type: 'SET_RANGE', payload: { value: 'Weekly', start: mome ...

What is the best way to present sorted items on a user interface?

I have a unique Med interface containing properties like drugClass, dosage, and name. Using this interface, I created an array of drugs with different attributes. How can I filter this array by drugClass and then display the filtered data on a web page? ...

Using TypeScript to send state through history.push({...})

I recently utilized the history.push method to redirect to a specific URL while passing along some information through the included state. Here's how I implemented it: const history = useHistory() history.push({ pathname: '/someurl/', ...

Automatically expand all PrimeNG Accordion panels for easy printing purposes

I've implemented the PrimeNG library's accordion component in my angular project. You can find more information here. In my template, I have some custom css styling for printing the page that looks like this: @media print { .profile-progress ...

Having difficulty transferring data between components using @Input syntax

I am having trouble passing the FailedProductId from Component1 to Component2 using @Input. Below is the code snippet: export class Component1 implements OnInit { public FailedProductId="produt"; constructor(private employeeService: ProductService) {} ...