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

  • 本文关键字:对象 传输 存在 如果 typescript
  • 更新时间 :
  • 英文 :


我从数据库中接收到一些数据,我想以某种方式格式化它。但是在尝试格式化它时,我遇到了一些困难。我将如何处理这个使用枚举作为基本对象的键的 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 将key的类型推断为string

所以myObject[key]是一个错误,因为myObject不能按string索引。 文字'a''b'是必需的。

相反,您希望它推断key属于keyof typeof someFetchedObject类型。

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

for (let key of Object.keys(someFetchedObject) as (keyof typeof someFetchedObject)[]) {
//...
}

我们使用Object.keys来获取一个属性名称数组,然后我们可以转换这些名称。它通常是string[],但我们可以从someObject中投射出一个键数组。请注意,我还将循环更改为for of而不是for in,因为我们现在正在迭代数组。

操场

最新更新