Home > Blockchain >  Angular Observable reduce function error "Type 'true' is not assignable to type '
Angular Observable reduce function error "Type 'true' is not assignable to type '

Time:03-16

I have a code in which the memberships$ is an observable of objects that have a property "role". I want to use reduce function in order to traverse all of them, and if anyone's role is "Collector" I want to return value true. This is the code:

hasCollectorRole$: Observable<boolean> = this.memberships$.pipe(
    map(arr => {
      return arr.reduce((acc, val) => {
        if (val.role == "Collector") {
          acc = true;
        }
        return acc;
      }, false)
    })
  );

This is the error that I get on it:

Type 'true' is not assignable to type 'false'.

How do I fix this?

CodePudding user response:

Try specifying the reducer's default value's type via:

arr.reduce(..., false as boolean)

Right now, it looks like TS thinks the type that should be returned is false, not boolean, and true is not assignable to type false.

CodePudding user response:

You should probably use .some() instead of .reduce() if you want to traverse a list and see if any role equals "Collector"

hasCollectorRole$: Observable<boolean> = this.memberships$.pipe(
  map(arr => {
    return arr.some((val) => val.role === "Collector")
  })
);

const testCollector = ['test', 'Collector'];
const testNoCollector = ['test', 'NotCollector'];

console.log('result with Collector', testCollector.some(t => t === 'Collector'));
console.log('result Without Collector', testNoCollector.some(t => t === 'Collector'));

  • Related