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

The identifier 'before' could not be located

While working with jest and typescript, I encountered an issue when using "before" calls: Cannot find name 'before'.ts(2304) I made sure to have @types/jest installed already. Update: It appears that jest does not have a "before" function - it ...

Inquiring about Vue 3 with TypeScript and Enhancing Types for Compatibility with Plugins

I've been struggling to find a working example of how to implement type augmentation with Vue3 and TypeScript. I have searched for hours without success, trying to adapt the Vue2 documentation for Vue3. It appears that the Vue object in the vue-class ...

Deduce the generic types of conditional return based on object property

My goal is to determine the generic type of Model for each property. Currently, everything is displaying as unknown[] instead of the desired types outlined in the comments below. playground class Model<T> { x?: T } type ArgumentType<T> = T ...

Switching templates based on elementRef width adjustments

I am facing an issue where I am trying to load some data in ngInit and set the width of a div equal to the received data. However, when I try to set some style options in ngAfterViewInit using ViewChild and ElementRef, my elementRef ends up being undefined ...

Problem encountered in a simple Jest unit test - Unexpected identifier: _Object$defineProperty from babel-runtime

Struggling with a basic initial test in enzyme and Jest during unit testing. The "renders without crashing" test is failing, as depicted here: https://i.stack.imgur.com/5LvSG.png Tried various solutions like: "exclude": "/node_modules/" in tsconfig "t ...

Tips for passing TouchableOpacity props to parent component in React Native

I created a child component with a TouchableOpacity element, and I am trying to pass props like disabled to the parent component. Child component code: import React from 'react'; import {TouchableOpacity, TouchableOpacityProps} from 'react- ...

The module '@ngmodule/material-carousel' could not be located

Having an issue with Angular 8 where I am encountering an error when trying to import the @ngmodule/material-carousel module. The specific error message is: Cannot find module '@ngmodule/material-carousel' Package.json "private": true, "depen ...

Is it possible to utilize useRef to transfer a reference of an element to a child component?

When I want to mount something into the element with id tgmlviewer, I call it a viewer object. This process works smoothly when there is only one component of this kind. import React, { useEffect } from "react"; import { Viewer } from "../.. ...

Executing the plugin-typescript library within an Angular 2 project hosted on localhost

I am encountering an issue every time I run my angular2 project where numerous files are being loaded, including the 'ts' library from unpkg.com/plugin-typescript/lib/plugin.js. I am looking to eliminate the need for this file to load from anothe ...

gather and handle data from the shared interface between different parts

I have two different paths. One is for products and the other is for products-cart. I want to use a shared ts file for both to store the product and cart information in an array. However, I am encountering an issue. I am unable to make any changes or trans ...

employing a variable within a function that is nested within another function

I'm encountering an issue where I am using a variable within a nested function. After assigning a value to it, I pass it to the parent function. However, when I call the function, nothing is displayed. function checkUserExists(identifier) { let user ...

An error occurred: The property 'toUpperCase' cannot be read of an undefined Observable in an uncaught TypeError

Encountering an issue during the development of a mobile app using the ionic framework for a movie application. After finding an example on Github, I attempted to integrate certain functions and designs into my project. The problem arises with the 'S ...

Need help with creating a unit test for the Material UI slider component? An error message saying "Error: Cannot read property 'addEventListener' of null" is displayed when trying to render the component

Encountered a problem while testing the Material-UI Slider with React-Test-Renderer: Uncaught [TypeError: Cannot read property 'addEventListener' of null] Codesandbox Link import React from "react"; import { Slider } from "@materi ...

Angular: bypassSecurityTrustHtml sanitizer does not render the attribute (click)

I'm facing an issue where a button I rendered is not executing the alertWindow function when clicked. Can anyone help?: app.component.ts: import { Component, ElementRef, OnInit, ViewEncapsulation } from '@angular/core'; import ...

Troubleshooting import errors with Typescript for C3 and D3 libraries

I have recently started working on a project using the C3 graphing library within an Ionic2/Angular2 TypeScript setup. After installing C3 via npm and the type definitions via tsd, I imported it into my own TypeScript file like this: import {Component} fr ...

The parent class has not been specified

I am facing an issue with my parent class, HTTPConnection, which I intend to use as a network utility class in order to avoid redundant code. However, when attempting to utilize it, the file core.umd.js throws an error stating Uncaught ReferenceError: HTTP ...

Can you explain the significance of the "type" reserved word in TypeScript?

When attempting to construct an interface in TypeScript, I discovered that the word "type" is both a keyword and a reserved term. In Visual Studio 2013 with TypeScript 1.4, for instance, when defining the following interface: interface IExampleInterface { ...

Troubleshooting Angular 2 Fallback Route Failure

My current project is using Angular 2 Webpack Starter but I am having trouble with the fallback route. In my app.routes.ts file, I have defined the routes as follows: import { Routes } from '@angular/router'; import { HomeComponent } from &apos ...

What is the reason behind TypeScript's restriction on referring to const variables in type definitions?

Defining a type that restricts the input string to two possible values can be done like this: type STATE_TYPE = 'DRAFT'|'PUBLISHED' function myFunc(state: STATE_TYPE) { ... } However, when trying to define the two values as const and ...

Error code -8 occurred while executing the yarn dev command, unable to identify the issue

I'm facing an issue with my development script that is structured like this: "scripts": { "dev": "./test.sh", }, Upon running the 'yarn dev' command, I encounter the following error message: Internal Error: ...