arunmmanoharan
arunmmanoharan

Reputation: 2675

Errors when mapping over an array of objects and introducing a new property - Typescript

I have an array of objects and I would like to loop over them and introduce a new property called 'colors' based on the value of 'y'.

The function works fine as expected, however I get some compile errors.

This is my code:

interface IChartData {
  name: string;
  y ? : number;
  isSum ? : boolean;
}

interface IColorChartByValue extends IChartData {
  color: string;
}

const colorChartByValue = (
  data: IChartData[]
): IColorChartByValue[] => {
  return data.map((item: IChartData, index: number, array: IChartData[]) => {
    if (index === 0 || index === array.length - 1) {
      item.color = '#137cbd'
    } else if (item.y >= 0) {
      item.color = '#0F9960'
    } else if (item.y < 0) {
      item.color = '#D9822B'
    }
    return item;
  });
};


const chartData: IChartData[] = [{
    name: 'Base Case',
    y: 100000,
  },
  {
    name: 'Waterfall 1',
    y: 11500,
  },
  {
    name: 'Waterfall 2',
    y: 5677,
  },
  {
    name: 'Waterfall 3',
    y: -3001,
  },
  {
    name: 'Waterfall 4',
    y: 6500,
  },
  {
    name: 'Upside',
    isSum: true,
  },
]

console.log(colorChartByValue(chartData))

This is the playground link: Link

Any help is appreciated. Thanks.

Upvotes: 1

Views: 32

Answers (1)

johannchopin
johannchopin

Reputation: 14843

In you map you just mutate an IChartData item, but for TypeScript it's still an IChartData that doesn't match IColorChartByValue. To fix it, you will need to return an IColorChartByValue in your map, instead of mutate it:

    return data.map((item: IChartData, index: number, array:IChartData[] ) => {
    if (index === 0 || index === array.length - 1) {
      return {...item , color:'#137cbd'}
    }
    // ...

Check the playground.

Upvotes: 2

Related Questions