Typescript 如果对象1中存在键,如何将值从对象2传输到对象1

Typescript 如果对象1中存在键,如何将值从对象2传输到对象1,typescript,Typescript,我从数据库中接收到一些数据,我想以某种方式对其进行格式化。但是当我尝试格式化它时,我遇到了一些困难。我将如何处理使用枚举作为基本对象键的senario。然后,检查第二个对象,如果该键与对象1的键匹配,则获取值,然后将其放置在对象1中 其思想是拥有某种已经具有默认值的基本对象。我使用枚举作为键,因为我希望在每次更改枚举时都更改对象。但是我有一些错误 enum test { empty = '', first = 'a', second = 'b', third =

我从数据库中接收到一些数据,我想以某种方式对其进行格式化。但是当我尝试格式化它时,我遇到了一些困难。我将如何处理使用枚举作为基本对象键的senario。然后,检查第二个对象,如果该键与对象1的键匹配,则获取值,然后将其放置在对象1中

其思想是拥有某种已经具有默认值的基本对象。我使用枚举作为键,因为我希望在每次更改枚举时都更改对象。但是我有一些错误

enum test {
    empty = '',
    first = 'a',
    second = 'b',
    third = 'c'
}

type defaultObject = {
    [test.first]: string,
    [test.second]: string,
    [test.third]: string
}

const myObject = {
    [test.first]: 'notImportant',
    [test.second]: 'notImportant',
    [test.third]: 'notImportant'
} as defaultObject;

const someFetchedObject = {
    a: 'notImportant2',
    b: 'notImportant2',
}

for (let key in someFetchedObject)
    if (key in myObject) {
        console.log(key);
        console.log(myObject[key]); //Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ a: string; b: string; c: string; }'.
        console.log(someFetchedObject[key]); //Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ a: string; b: string; }'
        myObject[key] = someFetchedObject[key]; // This is what I want to do
    }

//console.log(myObject);
// Should output {a:'notImportant2', b:'notImportant2', c:'notImportant'}

Typescript将
键的类型推断为
字符串

因此
myObject[key]
是一个错误,因为
myObject
不能被
string
索引。文本
'a'
'b'
是必需的

相反,您希望它推断
key
的类型为
keyof-typeof-someFetchedObject

发生这种情况的原因是(大多数情况下)当您迭代typescript中的键时,它可能有其他不属于接口的键。但是,在这种情况下,您可以确保只存在所需的关键点,因此可以使用强制转换

for (let key of Object.keys(someFetchedObject) as (keyof typeof someFetchedObject)[]) {
  //...
}
我们使用
Object.keys
来获得一个属性名数组,然后可以对其进行强制转换。它通常是
string[]
,但我们可以从
someObject
中对其强制转换一组键。请注意,我还将of
的循环更改为
,而不是in
中的
,因为我们现在正在迭代数组