Transfer characteristics from one object to another object using TypeScript

I have two objects with various properties. My goal is to transfer properties from one object to the other only if they are defined.

Below is the interface for the objects:

interface Settings {
  locale: string;
  currency: string;
  style: string;
  isDark: boolean;
  // Additional fields here
}

The two objects are initialized as follows:

const settings: Settings = {/*assign all fields here*/}
const settingsChange: Partial<Settings> = {/*change some fields*/}

My task now is to update the fields in settings based on the values in settingsChange, similar to how it's done in JavaScript

Object.entries(settingsChange).forEach(([key, value])=>{
  settings[key] = settingsChange[key] || settings[key]
})

This results in a TypeScript linting error:

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

How should I approach this issue? While I am aware that using Object.assign would resolve it, I prefer utilizing Object.entries for more flexibility in implementing custom logic.

Answer №1

newSettings = {
  ...settings,
  ...changesToSettings
};

If you need to perform some logic on the values, you can use the following approach:

newSettings = Object.fromEntries(Object.entries(settings).map(([key, value]) => {
  const updatedValue = (changesToSettings as keyof Settings)[key] ?? value;
  return [key, updatedValue];
})) as Settings;

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

What is the proper way to handle a 504 response header in an AJAX request using jQuery?

Recently, I encountered an issue with an AJAX call from the client that caught my attention. Here is a snapshot of how it looked: $.ajax({ 'url': '/converter/ajax-make-corrections/', 'data': { ...

Using JavaScript to access array INDEX values sequentially

I have created a Stacked Bar chart using the Js library dhtmlx, and here is the generated output: The JSON data is structured as follows: var data = [ { "allocated":"20", "unallocated":"2", "day":"01/01/2014" }, { "allocated":"12", "unallocated": ...

Interfacing between JavaScript and Objective-C on iOS devices

One method of communication between iOS and JavaScript involves creating fake URLs in JavaScript and appending a string as a parameter to Objective-C code. This URL is then parsed in the delegate method: -(BOOL)webView:(UIWebView *)webView shouldStartLoad ...

Create a new URL using `window.URL.createObjectURL` and specify the filename to open the PDF

Is there a way to customize the filename in createObjectURL of the blob? Currently, it generates a URL like this: <URL>/bfefe410-8d9c-4883-86c5-d76c50a24a1d const data = window.URL.createObjectURL(newBlob); const pdfWindow = window.open(); pdfWindo ...

Saving the current date in MongoDB using the save method

Is there a way to have MongoDB automatically populate a field with the current UTC DateTime when saving a document? I'm aware of the $currentDate operator, but it seems to only be accessible within the update method. ...

Getting the referer in getStaticProps: A simple guide

Is there a way to access the referer in the getStaticProps method? I am familiar with how to do it using getServerSideProps, but unsure about getStaticProps. In getServerSideProps: context.req.headers.referer; Using JavaScript: document.referer; What is ...

The JSON data in ajax is not formatted correctly

Hey everyone, I'm facing a really frustrating error. I have a JSON formatted array that I'm passing from a PHP script to JavaScript through AJAX. Despite validating the JSON output, I keep encountering an error at the jQuery.parseJSON() step, whi ...

Looking to implement pagination in Vue.js - what steps should I take?

Hi there, I'm currently facing an issue while trying to paginate my data. The error message in my console reads: Property or method "$index" is not defined on the instance but referenced during render. Below is my HTML template where I display the da ...

Ways to send information to browser javascript from Spring MVC controller

Looking for the most efficient method to transfer data from Spring MVC to JavaScript. Let's say there is an array in JavaScript: var myArray = new Array(); And in the Java backend, there is another array: int[] myArray = new int[100]; What would ...

After 60 seconds, the AJAX call is returning a 200 status code despite the fact that the server-side process is still

When implementing an AJAX call, I followed this structure: $.ajax({ url: 'download', type: 'POST', data: JSON.stringify(postData), cache: false, contentType: 'application/json;charset=UTF-8' }) . ...

Joining the Parent Route String with a Variable using Angular Routerlink

How can I incorporate string interpolation or concatenation into the router link below in order to navigate to the parent route and include a variable link? <a routerLink="../account-information/{{item.productId}}"> ...

What could be the reason behind the undefined return value of val()?

When I click a button, my script is supposed to get the value of the next hidden input field. However, it always returns "undefined". What could be causing this issue and why does val() return undefined? If I only try to select the element with next(' ...

Toggle the visibility of items by clicking on them

I am looking to toggle the visibility of elements on a timeline based on the selected year. For example, if a user clicks on the year 2015, all child elements should be hidden. If the user clicks on the same year again, the elements should then be shown. ...

Interactive calendar feature with a popup that appears when hovering over an event

I am looking to create a popup on hover with full calendar functionality, similar to the one seen at this link. I have attempted using full calendar with qtip, but I was unable to achieve a clickable popup as it disappears when the mouse moves away. Here ...

Is It Possible to Create Flash Content Without Using a SWF File?

Is there a way to embed Flash directly in HTML, rather than linking to an external SWF file? I am looking to send an HTML form via email for the recipient to fill out by opening it in a browser. The final step would involve copying the result to their clip ...

Difficulty in modifying an object's property/value using a variable within a function

VueJS is the framework I am currently working with and I am attempting to utilize v-model to link checkboxes to values stored within an object: jobsChecked: {Baker: false, Cook: false, Miner: false} // etc... Here is the checkbox element setup: <div c ...

Windows npm configuration settings

After receiving helpful answers to my previous question about using a named parameter in an npm run script, I encountered a new problem. It seems that the $npm_config_variable doesn't function correctly on Windows OS. I am in search of a solution that ...

Obtain the text from an altered stylesheet in Firefox

I am currently programmatically updating stylesheets for a web page using JavaScript. My method involves having a local copy of the page and all associated assets stored on a server. After I finish making changes to the stylesheets, my goal is to save the ...

Issue with jQuery selection in ChromeI'm experiencing a problem with

After entering a value into an input, I have code that should run when the focus exits the input field. $("#guest-level option[id='"+ result.BookingInfo.guestLevelCode +"']").attr("selected", "selected"); This code runs smoothly in Firefox but ...

Incorporating a JavaScript object into a DataTables JSON structure: A practical guide

I have integrated the datatables jQuery plugin into my project and I am looking to streamline the process by creating a shared function to easily call a datatable from multiple pages without duplicating code. To achieve this, I am attempting to define the ...