简体   繁体   中英

Assign properties from an object to another object in typescript

I two objects with many properties. I want to copy properties from one object to the other only if it's defined.

Here is the object interface:

interface Settings {
  locale: string;
  currency: string;
  style: string;
  isDark: boolean;
  // There are more fields here
}

The two objects are defined like this:

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

Now I need to assign the fields in settingsChange to settings , I am trying to do this just like I were to do it in javascript

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

Here is the typescript linting error I receive:

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 do I solve this ? I know that Object.assign would work but Object.entries gives me more freedom to apply whatever logic I need.

settings = {
  ...settings,
  ...settingsChange
};

You can do something like this if you need to do some logic on the values:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM