[Fixed] Reduce error type param pipe transform Angular

Issue

I created a transform pipe to reduce a list of objects

export class SumPipe implements PipeTransform {
  transform(items: ListCount[], attr: string): number {
    return items.reduce((a, b) => a + b[attr], 0);
  }
}

this the model of ListCount :

export interface ListCount {
  centre?: string;
  cause?: string;
  Time?: number;
}

but I have this error :

 error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ListCount'

Any help please

Solution

As mentioned in HTN answer, using attr: keyof ListCount tighten the typings for the attr parameter but because ListCount has both string and number value properties you need to validate if the attribute you are getting from b is of type number using typeof.

export class SumPipe implements PipeTransform {
  transform(items: ListCount[], attr: keyof ListCount): number {
    return items.reduce((a, b) => {
      // get `attr` value from `b`
      const value = b[attr];
      // validate if type of `b[attr]` is number
      // - if so do the addition
      // - otherwise return previous `a` value
      return typeof value === 'number' ? a += value : a;
    }, 0);
  }
}

Leave a Reply

(*) Required, Your email will not be published