The element is inferred to have the 'any' type. No index signature matching the parameter type 'string' was found on the 'User1' type

I have been experimenting with computed properties in TypeScript, but I've encountered a specific issue:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'User1'.
  No index signature with a parameter of type 'string' was found on type 'User1'

Below is the code snippet causing the error:

type User1 = {
  name: string;
  age: number;
  address: string;
};

const user1: User1 = {
  name: "user1",
  age: 23,
  address: "address",
};

let checkParameter: string | number = "name";
console.log(user1[checkParameter]); //error occurring here

checkParameter = "age";
console.log(user1[checkParameter]); //error occurring here

checkParameter = "address";
console.log(user1[checkParameter]); //error occurring here

The value of checkParameter is determined randomly at runtime.

I'm aiming for smooth execution without any errors.

Answer №1

To specify that User1 type has properties with keys of type string, you can use [key: string]: string

type User1  = {
   [key: string]: string;
   name: string;
   age: number;
   address: string;
};

const user1: User1 = {
   name: "user1",
   age: 23,
   address: "address",
};

let checkKey: string | number = "name";
console.log(user1[checkKey]);

If the possible key types for User1 include both strings and numbers, you can update the type definition like this:

type User1  = {
   [key: string | number]: string
   name: string;
   age: number;
   address: string;
};

Answer №2

To address this issue, one method could be to modify the type for checkParameter by creating a union of string types that represent each property.

let checkParameter: "name" | "age" | "address" = "name"

An alternative approach as recommended by @jcalz is to use keyof User1 in order to dynamically access properties of object User1:

type User1 = {
  name: string;
  age: number;
  address: string;
};

const user1: User1 = {
  name: "User 1",
  age: 23,
  address: "123 First St",
};

let checkParameter: keyof User1 = "name";
console.log(user1[checkParameter]); // User 1

checkParameter = "age";
console.log(user1[checkParameter]); // 23

checkParameter = "address";
console.log(user1[checkParameter]); // 123 First St

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

Experiencing memory issues while attempting to slice an extensive buffer in Node.js

Seeking a solution for efficiently processing a very large base64 encoded string by reading it into a byte (Uint8) array, splitting the array into chunks of a specified size, and then encoding those chunks separately. The current function in use works but ...

Tips for incorporating a multimedia HTML/JavaScript application within C++ programming

I possess the source code for a JavaScript/HTML5 application that operates on the client-side and manages the transmission/reception of audio and video data streams to/from a server. My objective is to develop a C++ application that fully integrates the c ...

Steer clear of mentioning unbound methods, as they can lead to accidental scoping errors with 'this' when invoking static methods

I've been working on a method map based on a query from the Stack Overflow post linked here to assist me in dynamically calling a static method. But, I keep encountering this error message: Avoid referencing unbound methods that could lead to uninte ...

Issues may arise in Typescript when trying to return an array of data from a redux createAsyncThunk function

Below is the code I am using to retrieve a list of users: export const fetchUserById = createAsyncThunk( "users/fetchById", async (_, { rejectWithValue, fulfillWithValue }) => { try { const response = await fetch(`https://reqres. ...

VueJS refreshes components while preserving previous data

As a newcomer to VueJs, I am currently working with a Practice component that includes an ExerciseMC component. The parent component retrieves a question object (with a text property) from the backend through a request and passes it as a prop to the Exerci ...

Encountering numerous errors when importing Wallet Connect / Web3 Provider

I encountered some challenges when trying to incorporate the "@walletconnect/web3-provider" JS library into my project. After installing the library along with the Web3 module using the following command: npm install --save web3 @walletconnect/web3-provide ...

Navigate JSON Object - Prior Action

I am looking for a solution related to the following question/answer: How can I cycle through JSON objects one by one in AngularJS on click I need help with a function that displays the previous item from a JSON object. When the first item is selected, c ...

"Make a phone call following the completion of an HTTP

Upon receiving and storing data, I am looking to execute a function but the code I currently have is not producing the desired result. Could someone provide some insight into what I might be doing incorrectly? Here's my current code snippet: $h ...

What is the method for triggering the output of a function's value with specified parameters by clicking in an HTML

I am struggling to display a random number output below a button when it is clicked using a function. <!DOCTYPE html> <html> <body> <form> <input type="button" value="Click me" onclick="genRand()"> </form> <scri ...

Leveraging a shared directory within an npm project

In my Vue project, I have multiple clients with similar components stored in a "common" folder structure: clients -- client1 ---- ... -- client2 ---- ... -- client3 ---- ... -- common ---- imports.js ---- ... Currently, each project has its own package.j ...

React-router can manage non-matching paths by utilizing a basic JavaScript router configuration

Is there a way to manage non-matching paths using plain JavaScript in React router configuration? const rootRoute = { component: 'div', childRoutes: [ { path: '/', component: App, childRoutes: [ requir ...

Leveraging the power of async to streamline the serialization of operations with numerous layers of callbacks in Node

I'm relatively new to working with node.js and I'm encountering difficulties in understanding callback functions. The issue arises when I need to execute a series of complex operations that involve a lot of code divided into modules with numerous ...

The proper way to implement global scripts in Next.js

I am currently working on implementing a global fade-in animation for all components in my application. By adding the className "fadeIn" to each element and setting the default opacity to 0, I then utilize JavaScript to change it to 1 when the element is v ...

Trouble with displaying a custom marker on Google Maps API v3

I have been struggling to replace the default marker with a custom icon in my Google Maps code. Despite my efforts and thorough research, I cannot seem to get it to work correctly. Below is the snippet of my code: <script type="text/javascript"> fu ...

Using Angular's ng-repeat to iterate through an array and display its objects within another array

One of my tasks involves retrieving json objects through a simple post method. The json contains multiple campaigns, organized in an array structure. Each campaign holds slots, which are also arrays with one or more base_image elements. My goal is to di ...

Need to return to the previous page following submission

Is there a way to redirect me to the premontessori page after I submit the form? Below is my function handleSubmit: handleSubmit(event) { event.preventDefault(); <Link to='/premontessori' style={{textDecoration:'none'}} & ...

Using JavaScript, adding an element to an array results in the array returning a value of 1

When I try to push a string into an array and then return the array, I am getting unexpected result of "1". Upon closer inspection, it seems that the array is being successfully created but before returning it, only "1" is being returned. Here is the snip ...

The user keeps finding themselves redirected back to the Home page rather than the page they are trying

Within my Angular application, users are authenticated through an OIDC provider using the library angular-auth-oidc-client. In the scenario where a user is not authenticated or their session has expired and they attempt to access a page such as https://loc ...

Make sure to concentrate on the input field when the DIV element is clicked

In my React project, I am working on focusing on an input element when specific buttons or elements are clicked. It is important for me to be able to switch focus multiple times after rendering. For instance, if a name button is clicked, the input box for ...

How can you extract the property names of the first object in an array of objects?

I have an array of objects with the following structure and I want to extract the property names of the first object from this array without including the values. The desired result should only be ["Name", "Account", "Status"] ...