javascripttypescriptangular7

How to add new property in the json data without adding in the interface using typescript or javascript


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
}

Solution

  • 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