Using TypeScript, leverage bracket notation to access a property of an object using a variable

I am working with an object that has an interface and I am interested in accessing values dynamically using property keys.

const userData: IUser = {
    username: "test",
    namespace: "test",
    password: "test"
}

Object.keys(userData).forEach(property=>{
    // Issue: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IUser'.
    console.log(userData[property]);
})

// This works
console.log(userData["username"]);

// This also works
const key = "username";
console.log(userData[key]);

Additionaly,

userData.hasOwnProperty(property)
does not solve the issue.

Answer №1

When using Object.keys, we are limited by the fact that it does not allow us to pass a generic type. The return type ends up being string[]. If we desire a type of [keyof IUser], we can achieve this by performing a type cast.

const keys: [keyof IUser] = Object.keys(tmpUser) as [keyof IUser]
keys.forEach((property)=>{
    console.log(tmpUser[property]);
})

However, this workaround is unnecessary. To easily access both the key and value of an object, you can simply use

Object.entries(tmpUser).forEach(([key,value])=>{
   
})

Answer №2

To define the data type for the keys in IUser as string (or a combination like string | number), you can use the following code:

interface IUser extends Record<string, any> {
    username: string
    namespace: string
    password: string
}

Answer №3

Here's another potential solution to consider. Assuming you have a function called process that takes an object and performs some action on it:


const process = <O extends { [key: string]: any }>(object: O) => {
    Object
        .keys(object)
        .forEach(prop => {
            // Now the issue is resolved
            console.log(object[prop]);
        });
}

process(tmpUser);

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

Issue with Typescript in Material-UI's CardActionArea component attribute

The documentation for Material-ui's Buttons | Third party routing library explains the need to create an adapter to wrap a react-router-dom/Link component in a Button. Interestingly, attempting the same with a CardActionArea (which is labeled as a Bas ...

How can I use a string variable in Angular 2 to create a dynamic template URL

@Component({ selector: 'bancaComponent', templateUrl: '{{str}}' }) export class BancaComponent implements OnInit { str: String; constructor(private http: Http) { } ngOnInit(): void { this.str = "./file.component.html"; } An ...

Issue with validating the date picker when updating user information

Trying to manage user accounts through a dialog form for adding and updating operations, where the type of operation is determined by a variable injected from the main component. Encountered an issue while launching the update process - the date picker tri ...

Looking to transform a timestamp such as "2021-07-18T9:33:58.000Z" into a more readable format like 18th July for the date or 9:33 am for the time using Angular?

Is there a way to convert the Timestamp format "2021-07-18T9:33:58.000Z" to display as 18th July (for date) or 9:33 am (for time) in an Angular 11 application? Currently, my code looks like this: const myDate = new DatePipe('en-US').transform ...

Puppeteer: implementing wait timeout is crucial to successfully handle Auth0 login process

Recently, I started using puppeteer and encountered some unexpected behavior. It seems that the waitForSelector function does not work properly unless I include a delay before it. Take a look at the following code: const browser = await puppeteer.l ...

Issues with using hooks in a remote module in Webpack 5 module federation

I am attempting to create a dynamic system at runtime using Module Federation, a feature in webpack 5. Everything seems to be working well, but I encounter a multitude of 'invalid rule of hooks' errors when I add hooks to the 'producer' ...

Changes in tabs are discarded when switching between them within Material UI Tabs

I have been experiencing an issue with the Material UI tab component where changes made in tabs are discarded when switching between them. It seems that after switching, the tabs are rendered again from scratch. For example, let's say I have a textFie ...

Remove a record from Angular 2 Firebase collection

I've been searching extensively for a solution to this problem. Despite following the documentation on AngularFire 2 and Angular 2, I am unable to find a working answer. My goal is simply to delete a specific entry in my Firebase database using its un ...

Having an issue with my code in angular 12 where I am unable to successfully call an API to retrieve a token, and then pass that token to another API for further processing

Here is the code snippet containing two methods: getToken and validateuser. I am fetching the token from getToken and passing it as a parameter to validateuser. However, before retrieving the token, my second API call is being executed. ...

Using Typescript with AWS Lambda can sometimes be a bit tricky. For example, when trying to invoke your Lambda function locally using "sam local invoke", you might encounter an error stating

Attempting to deploy an AWS Lambda function using the sam command with AWS's Hello World Example Typescript template, but encountering issues with the example template. Suspecting a bug within AWS causing this problem. This issue can be easily repli ...

Guide to implementing ES2022 modules within an extension

After making changes in my extension code to test various module types, I decided to modify my tsconfig.json file as follows: { "compilerOptions": { "declaration": true, "module": "ES2022", ...

`Angular 6 and the expiration of Jwt tokens`

I am currently developing an angular application that utilizes jwt for authenticating database calls. However, I encountered a problem where, when the token expires on the server, the app starts displaying blank pages instead of the expected data. This hap ...

React-query: When looping through useMutation, only the data from the last request can be accessed

Iterating over an array and applying a mutation to each element array?.forEach((item, index) => { mutate( { ...item }, { onSuccess: ({ id }) => { console.log(id) }, } ); }); The n ...

I possess a JSON array object and need to identify and extract the array objects that contain a specific child node

const jsonArray = { "squadName": "Super hero squad", "homeTown": "Metro City", "formed": 2016, "secretBase": "Super tower", "active": true, "members": [ { "name": "Molecule Man", "age": 29, "secretIdent ...

Exploring properties of nested elements in React

Picture a scenario where a specific element returns: <Component1> <Component2 name="It's my name"/> </Component1> Now, what I want to accomplish is something like this: <Component1 some_property={getComponent2'sN ...

Using HTTP POST to subscribe and implementing a try-catch block

When using Angular2's http.post, I encountered an issue where the headers were not sent to the CORS server. To address this, I attempted to create a loop that would retry the request until it succeeds. However, this resulted in an endless loop. How ca ...

Angular 5 error: The property you are trying to access is not defined in

I've been working on a simple class and I'm stuck trying to figure out why the "currentHost" variable is showing as non-existent. export class AppModule { public static currentHost: string = 'http://localhost:8080/'; constructor() ...

Modify the standard localStorage format

I'm encountering a dilemma with my two applications, located at mysite.com/app1 and mysite.com/app2. Both of these apps utilize similar localStorage keys, which are stored directly under the domain "mysite.com" in browsers. This setup results in the l ...

Error message: "Property 'item' is not found within type 'P' - The property is inaccessible in the higher order component even though it is included in the props."

I am currently learning about typescript and exploring how to use Higher Order Components (HoCs) with React in a specific scenario. In my case, I am trying to wrap a component with an HoC that checks whether the "item" passed into the "wrapped" component ...

What is the most effective way to send messages from Typescript to C#?

Could someone provide guidance on how to properly send a message from Typescript to C#? I have been attempting to receive the message in C# using WebView_WebMessageReceived with the code snippet below: private void WebView_WebMessageReceived(object sender, ...