Set a value to the field name within a variable in TypeScript

Can anyone help me with this problem?

type A {
  f1: string;
  f2; string;
}

I have a variable that holds the name of a field:

let fieldName: string = "f2";

I want to create an object using the fieldName:

{"content of fieldName": "sdf"}

Any suggestions on how to achieve this?

Answer №1

Starting with ES2015, the use of computed properties is now possible.

In your specific case, it would look like this:

{ [fieldName]: "sdf" }

Answer №2

To achieve this, simply utilize {[fieldName]:'sdf'}. You can also check out a live example on StackBlitz

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

Placing a blank object after every line within a TypeScript array

I'm currently working on creating an iterator using the .map() function, specifically in this way: const csv = this.invoices .map(data => ({ invoiceId: data.invoiceId, invoiceDate: data.invoiceDate, invoiceType: data.invoiceType, ...

When invoking the function, the original state remains unaffected within a separate function

Whenever I click on an 'item', it should establish an initial value for me to use in a comparison within another function that involves the mousemove event. However, when the mousemove function is triggered, the initial state remains at 0. imp ...

What is the best way to ensure a specific row remains at the bottom of an Angular table with Material when sorting?

My data table contains a list of items with a row at the end showing the totals. | name | value1 | value2 | --------------------------- | Emily | 3 | 5 | | Finn | 4 | 6 | | Grace | 1 | 3 | | TOTAL | 8 | 14 | I&apos ...

Cannot execute loop

I'm currently working on creating a loop within my component that involves making server calls: getBeds() { this.patientService.getBeds(this.selectedWard).subscribe( result => { console.log(result); this.beds = result; this.getBedDet ...

What is the best way to incorporate auto-completion into a browser-based editor using Monaco?

Recently, I embarked on a project to develop a browser-based editor using monaco and antlr for a unique programming language. Following an excellent guide, I found at , gave me a great start. While Monaco provides basic suggestions with ctrl + space, I am ...

Tips for identifying the cause of a memory leak in browser notifications

I am looking to implement browser notifications in a browser extension. However, I have noticed that the memory usage does not decrease after closing the notification. Can someone explain why this may be happening? Allow StackOverflow show notifications i ...

Struggling to solve a never-ending loop problem in a messaging application

I am currently in the process of developing a chat application. During the initialization of the chat page, I am checking for messages and storing them in an array. ngOnInit() { this.messageService.getMessages().doc(`${this.sortItineraries[0] + ...

Build a Google Map Widget within SurveyJs

Hey there, I'm new to working with SurveyJS and I'm trying to incorporate a Google Map widget into my SurveyJS. I followed some steps and successfully added the map in the Survey Designer section, but unfortunately, it's not loading in the T ...

What steps are involved in generating a Typescript module definition for a directory containing a babel-plugin-content-transformer?

Currently utilizing the babel-plugin-content-transformer to import a directory containing YAML documents in a React Native/Expo project. The configuration for my babel plugin looks like this: ['content-transformer', { transformers: [{ ...

Angular ngModel not updating both directions in data binding

<input matInput placeholder="username" [(ngModel)]="userId"> <input matInput placeholder="name" [(ngModel)]="name"> I have made sure to import the FormsModule in my Angular project. import { FormsModule ...

Discovering how to specify the type of a dynamically created object using 'for await' in TypeScript

for await (user of users) { ... } Encountered an issue: "error TS2552: Cannot find name 'user'. Did you mean 'users'?" Appreciate your assistance. ...

The 'BaseResponse<IavailableParameters[]>' type does not contain the properties 'length', 'pop', etc, which are expected to be present in the 'IavailableParameters[]' type

After making a get call to my API and receiving a list of objects, I save that data to a property in my DataService for use across components. Here is the code snippet from my component that calls the service: getAvailableParameters() { this.verifi ...

Restrictive discriminated union via function argument

I am in possession of a shop that organizes a variety of types based on their IDs interface Dog { type: "dog"; woofs: string; } interface Cat { type: "cat"; meows: string; } type Pet = Dog | Cat; type AnimalState = Record<string, Pet ...

Missing expected property in TypeScript casting operation

I recently came across this intriguing playground example outlining a scenario where I attempted to convert an object literal into an object with specific properties, but encountered unexpected results. class X { y: string; get hi(): string { ...

Issue: formGroup requires an input of type FormGroup. Please provide one; Error: Unable to access property 'controls' as it is undefined

In the process of building a login and registration form using Angular with .Net core, I encountered an error upon running the program. The error is showing up in the Browser Console tab. This is my userlog.component.ts file: import { Component, OnInit, O ...

Guide to invoking an API in Next.js 13 by utilizing specific variables within a client component

I currently have a collection of products that are accessible on my website through a straightforward function within a server component. async function getData() { const res = await fetch(`${apiPath}`); const data = (await res.json()) as PackProps ...

Why is @faker-js/faker not usable in a TypeScript project, showing undefined error, while the older "faker" import still functions correctly?

Currently, my packages.json file includes: "faker": "^5.5.3", "@types/faker": "^5.5.3", I am sticking with version 5.5.3 due to another project dependency (codecept) that requires this specific version. The ...

Typescript is struggling to accurately infer extended types in some cases

My goal is to optimize the body of a NextApiRequest for TypeScript. I currently have this code snippet: // This is a type from a library I've imported export interface NextApiRequest { query: Partial<{ [key: string]: string | string[]; ...

What could be causing NgModel to fail with mat-checkbox and radio buttons in Angular?

I am working with an array of booleans representing week days to determine which day is selected: selectedWeekDays: boolean[] = [true,true,true,true,true,true]; In my HTML file: <section> <h4>Choose your days:</h4> <mat-che ...

Searching is disrupted when the page is refreshed in NextJS

When I refresh the page, router.query.title disappears. I have read that I need to use getServerSideProps, but I'm unsure of what to include in the function. Can anyone provide guidance on how to resolve this issue? Update: I followed Yilmaz's s ...