18

I'm reading through some code with the snippet:

search(query: string) {
  of(query).
  pipe(
    filter(Boolean), 
    debounceTime(300), 

Is filter(Boolean) essentially the same thing as filter(v=>!!v)?

Ole
  • 41,793
  • 59
  • 191
  • 359

2 Answers2

15

Yes, they are the same.

   console.log(typeof Boolean); // prints function
   console.log(Boolean.prototype.constructor("truthy")); // prints true
   console.log(Boolean === Boolean.prototype.constructor); // prints true

The Boolean global reference points to the constructor function which returns a boolean value from the first argument.

The constructor can be used to create a boolean wrapper object, but it is not the same as the primitive true value.

    console.log(new Boolean("truthy")); // prints an object.
    console.log(new Boolean("truthy").valueOf() === true); // prints true
    console.log((new Boolean("truthy")) === true); // prints false
    console.log(Boolean("truthy") === true); // prints true

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean

Reactgular
  • 52,335
  • 19
  • 158
  • 208
15

They achieve the same result in that you don't get undefined values in your subscription.

The difference is that you lose Type Inference when using filter(Boolean)

const query = 'the query';

of(query).
  pipe(
     filter(Boolean)
  ).subscribe(val); // val here is of type 'Any'

of(query).
  pipe(
     filter(Boolean)
  ).subscribe((val: string)); // we can infer it back to string later

of(query).
   pipe(
      filter(v=> v!== undefined)
   ).subscribe(val); // val here is of type 'string' 
Corey Downie
  • 4,679
  • 3
  • 27
  • 29
  • 1
    Why do we lose type inference with filter(Boolean)? Is it related to TypeScript and/or RxJs? And is it documented by TypeScript and/or RxJs? – Marcus May 26 '20 at 23:05
  • 1
    @Marcus it's related to TypeScript. The above isn't correct. The type will be inferred as `boolean` because you passed the constructor function as the callback, and the `filter` type infers typing from the callback's first argument type. Which is `Boolean(val: boolean)`. You can define the type yourself as `filter(Boolean)` which tells the function what the observable type should be. Also, the above uses `String` when the original value was really `string`. The two types are not the same thing. – Reactgular Sep 24 '20 at 12:26
  • 1
    There used to be type issues. This is not true anymore with RxJS 7 - they fixed the type inference problem. – Alexey Grinko Dec 05 '21 at 11:02
  • You can somehow "restore" the expected `boolean` type by casting the filter operator `filter(Boolean)` – WSD Jul 03 '22 at 15:43