2

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?

0

2 Answers 2

1

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'));

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.