baconjs / bacon.js

Functional reactive programming library for TypeScript and JavaScript

Home Page:https://baconjs.github.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Observable.filter with type guard predicate

joux3 opened this issue · comments

Array.filter can change the type of the array when passed a user-defined type guard. See for example this:

// this gets inferred as (number | string)[]
const numberOrStringArray = [1, 2, 'jee']
// this is inferred as number[] thanks to the type guard
const numberArray = numberOrStringArray
  .filter((x): x is number => typeof x === 'number')

Could Observable.filter support a similar type guard? The type definition for Array.filter in the example is:

filter<S extends T>(callbackfn: (value: T, index: number, array: T[]) => value is S, thisArg?: any): S[];

This is a nice idea! Want to have a stab at this yourself?

Filter is a bit hard to modify, because it's already quite overloaded:

filter(f: Predicate<V> | boolean | Property<boolean>): this

A new operator on EventStream and Property can be added though:

  narrow<V2 extends V>(f: IsA<V, V2>): EventStream<V2> {
    return <any>filter<V>(this, f)
  }

What should we call it?