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)?
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
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'
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<string>(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.boolean type by casting the filter operator filter<boolean>(Boolean)