[英]TypeScript errors while trying to assign properties from one object to another
[英]Assign properties from an object to another object in typescript
我有兩個具有許多屬性的對象。 我想僅在已定義的情況下將屬性從一個對象復制到另一個對象。
這是對象接口:
interface Settings {
locale: string;
currency: string;
style: string;
isDark: boolean;
// There are more fields here
}
這兩個對象的定義如下:
const settings: Settings = {/*assign all fields here*/}
const settingsChange: Partial<Settings> = {/*change some fields*/}
現在我需要將settingsChange
的字段分配給settings
,我正在嘗試這樣做,就像我在 javascript 中所做的那樣
Object.entries(settingsChange).forEach(([key, value])=>{
settings[key] = settingsChange[key] || settings[key]
})
這是我收到的打字稿 linting 錯誤:
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)
我該如何解決這個問題? 我知道Object.assign
會起作用,但Object.entries
給了我更多的自由來應用我需要的任何邏輯。
settings = {
...settings,
...settingsChange
};
如果您需要對值執行一些邏輯,您可以執行以下操作:
settings = Object.fromEntries(Object.entries(settings).map(([key, value]) => {
const newValue = (settingsChange as keyof Settings)[key] ?? value;
return [key, newValue];
})) as Settings;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.