The type of the element is implicitly set to 'any' because the expression 'keyof IMyObj' cannot be used to index the type

Trying to avoid specifying types in TypeScript and setting a value by accessing its key is causing a TypeScript error. Despite looking at multiple StackOverflow posts, I couldn't find a solution.

I encountered a similar issue with my code and tried replicating it with a sample one.

type IMyObj = {
          title: string
          content: string
        }
        type IMyObj1 = {
          titles: string
          content1: string
        }
        const myObj: IMyObj = {
          title: 'Hi',
          content: 'Hope all is well',
        }
          const myObj: IMyObj1 = {
          titles: 'Hi',
          content1: 'Hope all is well',
        }



        const myKey: string = 'content'

        myObj[myKey as keyof IMyObj] = 'All is great now!'  // Element implicitly has an 'any' type because expression of type 'keyof IMyObj' can't be used to index type 'IMyObj | IMyObj1'.

Property 'title' does not exist on type 'IMyObj | IMyObj1'.ts(7053) No quick fixes available

The actual code is as follows:

I need to provide a type to currentValue passed to the method, so omitting the type here is not possible.

const formatData = (
    faData: FinancialSection[],
    faSection: keyof FinancialSection
  ) => ({
    ..._.sortBy(
      faData,
      (item: FinancialSection) => item.period.year
    ).reduce((actualValue: any, currentValue: FinancialSection) => {
      Object.keys(ProfitAndLossKeys).forEach((key: string) => {
        // eslint-disable-next-line no-param-reassign
        if (!actualValue[key]) actualValue[key] = { values: [] }
        actualValue[key].values.push(
          currentValue[faSection] && currentValue[faSection][key] !== null
            ? currentValue[faSection][key]    //Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ProfitLossData | KeyFiguresData | BalanceSheetData | CashFlowData | Period'.

No index signature with a parameter of type 'string' was found on type 'ProfitLossData | KeyFiguresData | BalanceSheetData | CashFlowData | Period'.ts(7053) : null ) }) return actualValue }, {}) })

Answer №1

The way you typed the object is incorrect.

const myObj: IMyObj | IMyObj1 =

This indicates to TypeScript that it could be either an IMyObj or an IMyObj1. However, the object actually contains properties of both, so you should use & instead of |.

const myObj: IMyObj & IMyObj1 = {

By making this adjustment, your error will be resolved - but it would be even simpler to omit the types completely and allow TS to infer them correctly.

const myObj = {
    title: 'Hi',
    content: 'Hope all is well',
    titles: 'Hi',
    content1: 'Hope all is well'
}
const myKey = 'content'

myObj[myKey] = 'All is great now!'

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

Access the child component within an @ChildComponent directive in Angular

Is it possible to retrieve child components of another component? For instance, consider the following QueryList: @ContentChildren(SysColumn) syscolumns: QueryList<SysColumn>; This QueryList will contain all instances of the SysColumns class, which ...

The VSCode Extension fails to launch after being packaged

I'm currently working on a straightforward VSCode extension that scans the active open file for any comments containing "//TODO: " and then presents a list of all TODO comments in a webview sidebar tab. While I have a functional prototype that runs s ...

Techniques for importing esm libraries without requiring the "type": "module" declaration in the package.json configuration file

I have successfully implemented a TypeScript Node project but now I am facing an issue while trying to integrate the VineJS library into the project. The problem arises because VineJS is exclusively an ESM (ECMAScript Module) package, and when adding it to ...

Transferring documents from an angular ionic application to a slim php framework on the localhost

Hey there! I've got a project on my localhost where I need to upload files to a local folder. I'm sharing the code here in hopes that someone can assist me. HTML: <ion-item ion-item *ngFor="let item of lista" menuClose> Floor: ...

Optimal method for importing libraries in Angular 2 with TypeScript

Currently experimenting with Angular2, but I find myself in need of using jQuery. After downloading the d.ts file, I referenced the definitions in each file using the following syntax: /// <reference path="../../../../typings/jquery/jquery.d.ts" /> ...

Error: The property 'process' cannot be read because it is not defined

Seeking help with a code issue Any advice on best practices would be greatly appreciated. Thank you! An error has occurred: TypeError: Cannot read property 'process' of undefined myComponent.ts ProcessInfo: any | false; showSaveItems = ...

Transform a 3D text rotation JavaScript file into an Angular component tailored TypeScript file

I have a javascript file that rotates text in 3D format, and I need help converting it into an Angular component specific TypeScript file. You can find the codepen for the original JavaScript code here. Below are my Angular files: index.html <!doctyp ...

Retrieve an item from an array using a Select component

Is there a way to retrieve the complete object representation of an item from a list in React? Currently, when I select an item and call handleChangeSelectAuto, the original value from useState is returned instead of the entire object. How can I ensure tha ...

Generics in Typescript implemented for a React component that accepts an array of records along with an array of

I am currently working on developing a straightforward typed react component designed to display a table from an array of objects. The input data is structured as follows: // array of records containing data to render in the table data = [ { one: 1, ...

How to refresh an array in Angular 4 after inserting a new element using splice method?

I have a Angular list displayed in a table, and I need to insert an element at a specific position. I have tried using the following code: array.splice(index, 0, element); While everything seems fine in the console with the element being added at the corr ...

Issue encountered when transitioning from Angular 8 to Angular 9: Value discrepancy at index 0

While updating my Angular project from version 8 to 9, I encountered an issue after following the update guide on update.angular.io and running npm update. When attempting to compile the website using ng serve, the following error occurred: ERROR in Faile ...

Assigning to a constrained type with an indexable signature results in failure

When using typescript 4.7.2, I encountered an issue where the following code fails only when assigning a value: type IndexableByString = { [k: string]: any }; function test<T extends IndexableByString>(target: T, key: string) { var prop = target ...

Is Typescript the Ultimate Replacement for propTypes in React Development?

After diving into Typescript for the first time and exploring related articles, it appears that when using Typescript with React, propTypes definitions may no longer be necessary. However, upon examining some of the most popular React Component Libraries: ...

Adding markers to a map in Angular 2 using ngOnInit after initialization

Embarking on my Angular journey by creating a sample app incorporating GoogleMaps. import { Component, Input, OnInit, Inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { FormControl } from '@ ...

Comparison between modules and standalone components

It has come to my attention that there is a growing trend in Angular 17 to move away from using modules, opting instead for standalone components. This approach makes Angular more similar to Vuejs or React, where the concept of modules is not as prominent. ...

Custom Angular directive for collapsing sub menus with CSS

I found a helpful article on creating collapsible menus and submenus using only Bootstrap and custom code for Angular 2, 4, 5, 6. I've been able to implement the logic successfully, but I'm facing an issue with multiple menus where clicking on an ...

Encountering the error message "The argument type 'AsyncThunkAction<*>' cannot be assigned to the parameter type 'Action<any>'" while trying to utilize a custom typed useAppDispatch hook

For a live example, you can check out this link. In the process of developing a React application with TypeScript and Redux Toolkit, I have meticulously followed the guidelines outlined in the documentation. As a result, I have successfully implemented ty ...

Filter an object in Typescript and retrieve a single key

Managing a set of checkboxes is essential in assigning roles to new users. While it's possible to filter and retrieve only the checked checkboxes, extracting just the "name" key poses a challenge. The current method involves filtering with a for loop ...

Mapping an array in Typescript using Angular to instantiate a class

I have received data from a web API that resembles the structure below. I am looking for guidance on how to properly map the product array into individual Products. My main objective is to convert the eating_time values into JavaScript datetime format. Cu ...

Prevent receiving the "deprecated warning for current URL string parser" by enabling the useNewUrlParser option

I recently encountered an issue with my database wrapper class that connects to a MongoDB instance: async connect(connectionString: string): Promise<void> { this.client = await MongoClient.connect(connectionString) this.db = this.cli ...