将 RxJS 与 filter(Boolean) 一起用于查询?

Using RxJS with filter(Boolean) for queries?

我正在阅读一些代码片段:

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

filter(Boolean)filter(v=>!!v) 本质上是一样的吗?

是的,它们是一样的。

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

Boolean 全局引用指向构造函数,returns 来自第一个参数的布尔值。

构造函数可以用来创建一个boolean包装器对象,但它与原始true值不同。

    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

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

他们实现了相同的结果,因为您不会在订阅中获得未定义的值。

区别在于使用 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'