Iterate through a type object to identify any undefined properties and then transfer them to another class object with matching fields

In my application, I have a class used for the database and a type received from the frontend.

The database class structure is as follows:

@ObjectType()
@Entity()
export class Task {
  @Field(() => Int)
  @PrimaryKey()
  id!: number;

  @Field(() => String)
  @Property({ type: 'date' })
  createdAt = new Date();

  @Field(() => String)
  @Property({ type: 'date', onUpdate: () => new Date() })
  updatedAt = new Date();

  @Field()
  @Property({ type: 'text' })
  name!: string;

  @Field(() => String)
  @Property({ type: 'date' })
  alertAt = new Date();

  @Field(() => Date)
  @Property({ type: TimeType})
  from: TimeType;

  @Field(() => Date)
  @Property({ type: TimeType})
  to: TimeType;

  @Field(() => Boolean)
  @Property({ type: 'boolean' })
  isDaily: boolean;
}

The type received from the frontend is defined as:

type TaskInput = {
  id: number,
  from: Date,
  to: Date,
  daily: boolean,
  alertAt: Date
}

When trying to update a Task object with TaskInput values, I encounter the error:

async updateTask(taskInput: TaskInput)
    const task = await em.findOneOrFail(Task, { id: taskInput.id })

    Object.entries(taskInput).forEach(([key, value]) => {
        if(value){
            task[key] = value;
        }
    })
}

However, the error message displays:

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

How can I address this issue?

Answer №1

If you need to update values in an object, you can use a function like the one shown below:

function modifyObject<K extends string,A extends {[key in K]:any}>(obj:A, key: K, value:any)
{
  if(value)
    obj[key]=value;
}

Object.entries(inputData).forEach(([key, value]) => {
      modifyObject(data,key,value)
})

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

A universal TypeScript type for functions that return other functions, where the ReturnType is based on the returned function's ReturnType

Greetings to all TypeScript-3-Gurus out there! I am in need of assistance in defining a generic type GuruMagic<T> that functions as follows: T represents a function that returns another function, such as this example: fetchUser(id: Id) => (disp ...

Troubleshooting: NextJS Typescript getInitialProps returning null value

I am currently working with NextJS 'latest' and TypeScript to extract the token from the URL, but I am encountering an issue where it returns undefined. To achieve this, I am utilizing the getInitialProps method. The URL in question looks like th ...

Tips for correctly specifying the types when developing a wrapper hook for useQuery

I've encountered some difficulties while migrating my current react project to typescript, specifically with the useQuery wrappers that are already established. During the migration process, I came across this specific file: import { UseQueryOptions, ...

JavaScript: exporting everything from ... causing excessive bloat in the build file

After building my react-app with create-react-app, I noticed a decline in performance. Here is the structure of my project: /store actions.ts reducers.ts /module1 module1.actions.ts module1.reducers.ts /moduleN moduleN.actions.ts m ...

Using sl-vue-tree with vue-cli3.1 on internet explorer 11

Hello, I am a Japanese individual and my proficiency in English is lacking, so please bear with me. Currently, I am using vue-cli3.1 and I am looking to incorporate the sl-vue-tree module into my project for compatibility with ie11. The documentation menti ...

Validation of object with incorrect child fields using Typeguard

This code snippet validates the 'Discharge' object by checking if it contains the correct children fields. interface DischargeEntry { date: string; criteria: string; } const isDischargeEntry = (discharge:unknown): discharge is DischargeEntry ...

How can you ensure an interface in typescript 3.0 "implements" all keys of an enum?

Imagine I have an enum called E { A = "a", B = "b"}. I want to enforce that certain interfaces or types (for clarity, let's focus on interfaces) include all the keys of E. However, I also need to specify a separate type for each field. Therefore, usi ...

Troubleshooting: Angular input binding issue with updating

I am currently facing a challenge with connecting a list to an input object in Angular. I was expecting the updated values to reflect in the child component every time I make changes to the list, but strangely, the initial values remain unchanged on the sc ...

Just starting out with React and encountering the error: Invalid element type, a string was expected

I seem to be going in circles with the following issue as I try to load the basics of a React app into the browser. An error message stating 'Element type is invalid: expected a string (for built-in components) or a class/function (for composite c ...

Guide to incorporating a pluck feature into TypeScript code

One task I face frequently is extracting specific properties from an object const obj = {a:1, b: 2, c: 3}; const plucked = pluck(obj, 'a', 'b'); // {a: 1, b:2} Unfortunately, achieving this task with type safety in TypeScript can be c ...

Issue with NgModule in Angular application build

I'm facing an issue with my Angular application where the compiler is throwing errors during the build process. Here's a snippet of the error messages I'm encountering: ERROR in src/app/list-items/list-items.component.ts:9:14 - error NG6002 ...

Adding Profile Photos to Authenticated User Accounts in Firebase / Ionic: A Step-By-Step Guide

I have thoroughly gone through the Firebase Docs on "Managing Users" for web along with watching their instructional video on YouTube. Despite following the code they provide, I am encountering an error message that states: "Property 'afAuth' do ...

Tips for isolating data on the current page:

Currently, I am using the igx-grid component. When retrieving all data in one call and filtering while on the 3rd page, it seems to search through the entire dataset and then automatically goes back to "Page 1". Is there a way to filter data only within th ...

Tips on using the map and filter methods to narrow down a nested array based on specific object

I am struggling to filter JSON data based on a specific date using Array.Filter and Map. The code I have tried below is not yielding the desired results. Can someone please provide guidance on how to effectively filter JSON data based on a particular date ...

A guide to testing the mui Modal onClose method

When using material UI (mui), the Modal component includes an onClose property, which triggers a callback when the component requests to be closed. This allows users to close the modal by clicking outside of its area. <Modal open={open} onCl ...

Encountering a problem with the chipGrid feature in Angular Material version

I am currently facing an issue with my angular material chip component. The versions I am using are Angular 16 and Material 16. Here are all my dependencies: "@angular/animations": "^16.0.4", "@angular/cdk": "^16.0.4&quo ...

Ionic 3: Struggling to Access Promise Value Outside Function

I've encountered an issue where I am unable to retrieve the value of a promise outside of my function. It keeps returning undefined. Here's what I have attempted so far: Home.ts class Home{ dd:any; constructor(public dbHelpr:DbHelperProvider ...

What could cause my arguments to "not align with any signature" of console.log?

Here is a basic class example: export class Logger { constructor(private name: string) {} debug(...args: any[]) { console.debug(...args) } log(...args: any[]) { console.log(...args) } } Despite being able to pass anything to console.l ...

What is the best way to ensure TypeScript recognizes a variable as a specific type throughout the code?

Due to compatibility issues with Internet Explorer, I find myself needing to create a custom Error that must be validated using the constructor. customError instanceof CustomError; // false customError.constructor === CustomError; // true But how can I m ...

Angular 5: Unable to add a destroyed View to a ViewContainer

I encountered a new error in my Angular application that I haven't seen before. The issue is arising from this specific line in the Angular source code. This error occurs when I log out and then log back into my app. While on a certain route, there i ...