1

I am trying to add new properties inside the josn data without adding in the interface. But i am not able to add it.So, How to add new properties in the json data. Is it possible or not?

app.component.ts:

export class AppComponent {
  data1: Candle[] = [
    {
      name: 'john',
      place: 'forest',
      phone: '124-896-8963'
    },
    {
      name: 'Jay',
      place: 'City',
      phone: '124-896-1234'
    },
    {
      name: 'Joseph',
      place: 'sky',
      phone: '124-896-9632'
    },
  ];

  foo() {
    const modifiedData = this.data1.map(d => {
      d.expanded1 = false; // error! 
      //~~~~~~~~~ Property 'expanded1' does not exist on type 'Candle'.
      d.expanded2 = false; // error! 
      //~~~~~~~~~ Property 'expanded2' does not exist on type 'Candle'.
      return d;
    });

    console.log(modifiedData);
  }
}
interface Candle {
  name: string,
  place: string,
  phone: string
}
6
  • I think the only way to do this, if you don't have access to the interface (or don't want to change it), is to extend the interface to have the new fields.
    – Dr_Derp
    Commented Nov 15, 2023 at 18:49
  • You could use Object.assign() like this. Does that meet your needs? If so I'll write up an answer explaining; if not, what am I missing?
    – jcalz
    Commented Nov 15, 2023 at 18:53
  • @jcalz:Please add your answer with stackblitz
    – sarann
    Commented Nov 15, 2023 at 19:07
  • I don't understand, are you asking me to use a particular web IDE? Like stackblitz in particular? Or are you just saying I should write up an answer because it meets your needs? Help, I'm confused.
    – jcalz
    Commented Nov 15, 2023 at 19:10
  • @jcalz: not working in stackblitz: console.log(modifiedData);
    – sarann
    Commented Nov 15, 2023 at 19:15

1 Answer 1

1

TypeScript doesn't really like to let you mutate the type of a value, and adding new properties to an object whose type isn't known to have them will give you a compiler error for good reason (this is quite likely to be a mistake). One way around this issue is to use the Object.assign() method, which mutates its first argument by adding properties from the remaining arguments. TypeScript's call signature for Object.assign() returns the intersection of the input types, which means the output is known to have all the properties of all the inputs.

That means we can change your code to

const modifiedData = this.data1.map(d => {
  return Object.assign(d, { expanded1: false, expanded2: false });
});
/* const modifiedData: (Candle & {
expanded1: boolean;
expanded2: boolean;
})[] */

And now modifiedData is known to be an array whose elements are Candle objects with two extra boolean properties, as desired.

Playground link to code

Not the answer you're looking for? Browse other questions tagged or ask your own question.