Skip to content

Commit

Permalink
fix: Add missing filter overload to allow for type narrowing (#149)
Browse files Browse the repository at this point in the history
  • Loading branch information
kitten authored Mar 10, 2023
1 parent e1b4c90 commit 6111f95
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/khaki-lemons-argue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'wonka': patch
---

Add missing overload definition for `filter`, which allows types to be narrowed, e.g. by specifying a type predicate return type.
6 changes: 4 additions & 2 deletions src/__tests__/operators.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,10 +231,12 @@ describe('filter', () => {
passesAsyncSequence(noop);

it('prevents emissions for which a predicate fails', () => {
const { source, next } = sources.makeSubject();
const { source, next } = sources.makeSubject<boolean>();
const fn = vi.fn();

sinks.forEach(fn)(operators.filter(x => !!x)(source));
sinks.forEach((x: true) => {
fn(x);
})(operators.filter((x): x is true => !!x)(source));

next(false);
expect(fn).not.toHaveBeenCalled();
Expand Down
10 changes: 7 additions & 3 deletions src/operators.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Source, Sink, Operator, SignalKind, TalkbackKind, TalkbackFn } from './types';
import { Push, Source, Sink, Operator, SignalKind, TalkbackKind, TalkbackFn } from './types';
import { push, start, talkbackPlaceholder } from './helpers';
import { fromArray } from './sources';

Expand Down Expand Up @@ -268,7 +268,9 @@ export function concat<T>(sources: Source<T>[]): Source<T> {
* );
* ```
*/
export function filter<T>(predicate: (value: T) => boolean): Operator<T, T> {
function filter<In, Out extends In>(predicate: (value: In) => value is Out): Operator<In, Out>;
function filter<T>(predicate: (value: T) => boolean): Operator<T, T>;
function filter<In, Out>(predicate: (value: In) => boolean): Operator<In, Out> {
return source => sink => {
let talkback = talkbackPlaceholder;
source(signal => {
Expand All @@ -280,12 +282,14 @@ export function filter<T>(predicate: (value: T) => boolean): Operator<T, T> {
} else if (!predicate(signal[0])) {
talkback(TalkbackKind.Pull);
} else {
sink(signal);
sink(signal as Push<any>);
}
});
};
}

export { filter };

/** Maps emitted values using the passed mapping function.
*
* @param map - A function returning transforming the {@link Source | Source's} values.
Expand Down

0 comments on commit 6111f95

Please sign in to comment.