在打字稿中访问对象键和设置值

问题描述 投票:0回答:1

在打字稿中,如何使用键获取对象值并使用相同的键获取对象 B 并设置 objA 值。如果两个对象属于同一类型。 例如:

 let objA = {
   a: 1,
   b: 'hello',
   c: null
 }

 let objB = {
   a: 2,
   b: null,
   c: 9
  }

for(let key in objA ) {
    if(objA[key] === null){
       objA[key] =  objB[key] !== null ? objB[key] : 0;
    }
}

但我遇到以下错误:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{ a: number; b:字符串; c: 空; }'。 在类型 '{ a: number; 上找不到参数类型为 'string' 的索引签名b:字符串; c: 空; }'.(7053)

typescript
1个回答
-1
投票

您看到的错误是因为当您使用 for..in 循环迭代对象的属性时,TypeScript 无法推断出键变量的类型。您可以通过将键变量的类型明确指定为字符串类型以及指定您正在使用的对象的类型来修复此错误

type MyObject = {
  a: number;
  b: string;
  c: null | number;
}

let objA: MyObject = {
  a: 1,
  b: 'hello',
  c: null
}

let objB: MyObject = {
  a: 2,
  b: null,
  c: 9
}

for (let key: keyof MyObject in objA) {
  if (objA[key] === null) {
    objA[key] = objB[key] !== null ? objB[key] : 0;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.