I have two objects of the same model:
interface Project {
_id?: string
title: string
description: string
goal: string
tasks?: Task[]
createdAt?: Date
updatedAt?: Date
}
The first object contains all fields from the interface, while the second object may contain some or all of these: title, description, goal.
I am trying to update the first object with values from the second object only if they are valid and relevant. Here's what I have so far:
const updateProjectUtil = (target: Project, update: Project): Project => {
Object.keys(update).forEach(key => {
const k = key as keyof Project;
if (target.hasOwnProperty(k) && update[k]) {
target[k] = update[k] // this line is causing a TypeScript error
}
})
return target;
}
I encountered this error message:
Type 'string | Task[] | Date | undefined' is not assignable to type 'string & Task[] & Date'. Type 'undefined' is not assignable to type 'string & Task[] & Date'. Type 'undefined' is not assignable to type 'string'.
I also tried using Object.entries but it didn't resolve the issue.
In the broader context: I am developing a RESTful API with Node.js and Express. This function belongs in the controller for the update route, where I receive an updated object from the client-side and an existing object from MongoDB, merge the necessary fields, save changes to the database, and send the updated data back to the client.
Any suggestions on how to address this error? Thank you.