typescript expended object show only firs added

Viewed 38
const obj = {
  num1 : 'string',
}
const obj2 = {
  num2 : 1234
}
let a = {
  ...obj,
}
a = {
  ...a,
  ...obj2,
}
a.num1 // ok
a.num2 // error

Object a contains first element num1 and dont show the second num2 in real code the obj and obj2 is complex and not same

enter image description here

1 Answers

From the definition of a, the type of a is limited to

const a: {
     num1: string;
}

While assigning { ...a, ...obj2} to a can satisfy this restriction condition, but when the variable a is used, its type is still the type when it was originally defined, so It will throw an exception, maybe you can try

const obj = {
   num1:'string',
}
const obj2 = {
   num2: 1234
}
const a = {
   ...obj,
}
const c = {
   ...a,
   ...obj2,
}
c.num1 // ok
c.num2 // ok

online

Related