Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
fix(TS): fix type inference for defaultIfEmpty. (#4833)
  • Loading branch information
bowenni authored and benlesh committed Jun 4, 2019
1 parent f31c3df commit 9b5ce2f
Show file tree
Hide file tree
Showing 4 changed files with 8 additions and 5 deletions.
6 changes: 5 additions & 1 deletion spec-dtslint/operators/defaultIfEmpty-spec.ts
@@ -1,5 +1,5 @@
import { of } from 'rxjs';
import { defaultIfEmpty } from 'rxjs/operators';
import { defaultIfEmpty, map } from 'rxjs/operators';

it('should infer correctly', () => {
const o = of(1, 2, 3).pipe(defaultIfEmpty()); // $ExpectType Observable<number>
Expand All @@ -13,6 +13,10 @@ it('should infer correctly with a different type of defaultValue', () => {
const o = of(1, 2, 3).pipe(defaultIfEmpty<number, string>('carbonara')); // $ExpectType Observable<string | number>
});

it('should infer correctly with a subtype passed through parameters', () => {
const o = of(true, false).pipe(map(p => p), defaultIfEmpty(true)); // $ExpectType Observable<boolean>
});

it('should enforce types', () => {
const o = of(1, 2, 3).pipe(defaultIfEmpty(4, 5)); // $ExpectError
});
3 changes: 1 addition & 2 deletions src/internal/operators/defaultIfEmpty.ts
Expand Up @@ -4,8 +4,7 @@ import { Subscriber } from '../Subscriber';
import { OperatorFunction, MonoTypeOperatorFunction } from '../types';

/* tslint:disable:max-line-length */
export function defaultIfEmpty<T>(defaultValue?: T): MonoTypeOperatorFunction<T>;
export function defaultIfEmpty<T, R>(defaultValue?: R): OperatorFunction<T, T | R>;
export function defaultIfEmpty<T, R = T>(defaultValue?: R): OperatorFunction<T, T | R>;
/* tslint:enable:max-line-length */

/**
Expand Down
2 changes: 1 addition & 1 deletion src/internal/operators/first.ts
Expand Up @@ -84,6 +84,6 @@ export function first<T, D>(
return (source: Observable<T>) => source.pipe(
predicate ? filter((v, i) => predicate(v, i, source)) : identity,
take(1),
hasDefaultValue ? defaultIfEmpty<T | D>(defaultValue) : throwIfEmpty(() => new EmptyError()),
hasDefaultValue ? defaultIfEmpty<T, D>(defaultValue) : throwIfEmpty(() => new EmptyError()),
);
}
2 changes: 1 addition & 1 deletion src/internal/operators/last.ts
Expand Up @@ -47,6 +47,6 @@ export function last<T, D>(
return (source: Observable<T>) => source.pipe(
predicate ? filter((v, i) => predicate(v, i, source)) : identity,
takeLast(1),
hasDefaultValue ? defaultIfEmpty<T | D>(defaultValue) : throwIfEmpty(() => new EmptyError()),
hasDefaultValue ? defaultIfEmpty<T, D>(defaultValue) : throwIfEmpty(() => new EmptyError()),
);
}

0 comments on commit 9b5ce2f

Please sign in to comment.