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.