Changing the value within an object by using a dynamic variable as the property name in Typescript

Here is a method that I have:

updateDate(row: TaskItem, column: keyof TaskItem, date: string) {
  row[column] = date;
}

The TaskItem interface is defined as follows:

export interface TaskItem {
  id: number,
  myDate: string
}

I would like to call the updateDate method like this:

updateDate(rowItem, 'myDate', '2022-02-20');

But TypeScript gives me an error:

Type 'string' is not assignable to type 'never'.ts(2322)

Changing row: TaskItem to row: any fixes the issue, but I prefer a more concise solution.

Answer №1

A neat solution is to use generics in order to safely handle any object type, ensuring that the second parameter is a valid key of obj and that the third parameter matches the type of typeof obj[key].

function updateProp<TObj, K extends keyof TObj>(obj: TObj, key: K, value: TObj[K]) {
    obj[key] = value;
}

interface TaskItem {
    id: number,
    myDate: string
}

declare const rowItem: TaskItem;

updateProp(rowItem, 'myDate', '2022-02-20');

Playground Link

Answer №2

The issue you are encountering is valid, as your updateDate function assumes that the new value (date) is of type string. However, since you are not specifying which specific field needs to be updated, there is a conflict because even if the new value is of type string, there is a chance that the column could be id (column: 'id' | 'myDate') which is not of type string but rather a number.

You can either modify the function updateDate to only handle updates for the myDate field:

function updateDate(row: TaskItem, date: string) {
  row.myDate = date
}

or include a condition to ensure that you update only the myDate field:

function updateDate(row: TaskItem, column: keyof TaskItem, date: string) {
  if (column === 'myDate') {
     row[column] = date
  }
}

Typescript playground

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

Can you tell me the data type of IconButtons in Material UI when using TypeScript?

Currently, I am in the process of creating a sidebar using Material UI in Next JS with typescript. My plan is to create a helper function that will help display items within the sidebar. // LeftSidebar.tsx import {List,ListItem,ListItemButton,ListItemIcon ...

InvalidAction: The function forEach cannot be applied to "res"

Here is the HTML code that I am currently working with: <div *ngIf="chart" class="col-xl-4 col-lg-6"> <div class="card cardColor mb-3"> <div class="card-header headColor"> <img class="img-fluid" src="../../../ ...

Get started with adding a Typescript callback function to the Facebook Login Button

I am in the process of implementing Facebook login into my Angular7 application using Typescript. Although I have successfully integrated Facebook's Login Button plugin for logging in, I am facing issues with providing a callback method to the button& ...

Older versions of javascript offered the assurance of a promise

Working with TypeScript and the latest ECMAScript 6 feature Promise at the moment. I'm wondering if it's possible to use Promise even if my TypeScript code is compiled into an ECMAScript 3 js-file, considering that Promise wasn't available i ...

Challenges with variable scopes and passing variables in Ionic 2 (Typescript)

In my Ionic 2 TypeScript file, I am facing an issue with setting the value of a variable from another method. When I close the modal, I get undefined as the value. I'm encountering difficulty in setting the value for coord. export class RegisterMapP ...

Using React with Typescript: Can the parent component access data fetched from a nested child component?

Can I access data retrieved from a child component (using a graphql query) in a parent component? For example, how can I use the data fetched by React-component-4 in React-component-1? Is there a way to do this or do I have to duplicate the data fetching ...

What is the best way to set up a property in a service that will be used by multiple components?

Here is an example of how my service is structured: export class UserService { constructor() {} coords: Coordinates; getPosition() { navigator.geolocation.getCurrentPosition(position => { this.coords = [position.coords.latitude, posit ...

Tips for modifying only one property after receiving an object from an HTTP GET request

Within my Angular application, I have defined an object structure like this: export class Article { id: number; author: number; title: string; content: string; date: Moment; readingTime: number; draft: boolean; constructor(obj: Partial< ...

Unpacking nested JSON objects with key-value pairs at various depths using TypeScript within a Node environment

Currently, I am faced with the task of parsing data at various levels in order to retrieve it while maintaining a consistent format. My project involves using TypeScript within the Node environment (specifically Google Cloud), and although I am relatively ...

Navigating the onSubmit with Formik in React: Tips and Tricks

I have a query regarding my usage of Formik in my React application. Within the onSubmit function, I am making an API call to a service. If this call fails, I want to immediately stop the rest of the submission process without executing any further action ...

Tips for extracting specific JSON response data from an array in TypeScript

I have an array named ReservationResponse, which represents a successful response retrieved from an API call. The code snippet below demonstrates how it is fetched: const ReservationResponse = await this.service.getReservation(this.username.value); The st ...

There are no imports in index.js and there is no systemjs configuration set up

After creating a fresh Angular project using ng new some-name, I noticed that the generated index.html file does not include any <script> tags and there is no SystemJS configuration either. Is this the expected behavior? I was anticipating the CLI ...

When parameters are added to one route, all other routes cease to function properly

After I added a parameter to one of the routes, all the other routes stopped rendering correctly (i.e., router-view is not working at all). The route /download/:id works as expected. Am I missing something in the setup? I tried leaving and removing the /do ...

Having trouble logging in with Google using React, Redux, and Typescript - encountered an error when attempting to sign in

As a beginner in TS, Redux, and React, I am attempting to incorporate Google Auth into my project. The code seems functional, but upon trying to login, an error appears in the console stating "Login failed." What adjustments should be made to resolve thi ...

When evaluating code with eval, properties of undefined cannot be set, but the process works seamlessly without

Currently, I am attempting to utilize the eval() function to dynamically update a variable that must be accessed by path in the format myArray[0][0[1][0].... Strangely enough, when I try this approach, I encounter the following error: Uncaught TypeError: ...

When using Inertia.js with Typescript, an issue arises where the argument types {} and InertiaFormProps{} are not compatible with the parameter type Partial<VisitOptions> or undefined

I set up a brand new Laravel project and integrated Laravel Breeze along with Typescript support. After creating a form (using useForm()) and utilizing the .post() method with one of the options selected (such as onFinish: () =>), I encountered the fol ...

Angular JS and TypeScript - Issue: ng:areq Invalid Argument "Argument 'XXXXXX' is not a function, received undefined"

Encountering a specific error mentioned in the title. I organized models and controllers into distinct files saved under models and controllers folders respectively. Upon trying to establish a connection between them, I received an error stating "ng:areq ...

NG build error: Module parsing failed due to an unexpected token - no updates made

Two days ago, out of nowhere, we started encountering build errors during deployment using GitLab CI. No alterations have been made to the build scripts, and none of the versions of NPM, NG, or Angular have been modified. The same compilation commands cont ...

I anticipated receiving an array of objects from the API response, but instead, I am dealing with an array of Promises in my React app using TypeScript

Apologies if this question seems basic to you. I am still new to TypeScript and working with Promises. Despite searching on various platforms, I couldn't find a relevant solution. Can you assist me in receiving an array of objects instead of promises? ...

Keying objects based on the values of an array

Given the array: const arr = ['foo', 'bar', 'bax']; I am looking to create an object using the array entries: const obj = { foo: true, bar: true, bax: false, fax: true, // TypeScript should display an error here becau ...