Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
fix(defer): restrict allowed factory types (#4835)
* test(defer): add failing dtslint test

* fix(defer): restrict allowed factory types

* test(defer): add a sometimes-returns dtslint test
  • Loading branch information
cartant authored and benlesh committed Jun 6, 2019
1 parent e4f2d23 commit 40a2209
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
10 changes: 9 additions & 1 deletion spec-dtslint/observables/defer-spec.ts
Expand Up @@ -18,4 +18,12 @@ it('should support union type returns', () => {

it('should infer correctly with void functions', () => {
const a = defer(() => {}); // $ExpectType Observable<never>
});
});

it('should error if an ObservableInput is not returned', () => {
const a = defer(() => 42); // $ExpectError
});

it('should infer correctly with functions that sometimes do not return an ObservableInput', () => {
const a = defer(() => { if (Math.random() < 0.5) { return of(42); } }); // $ExpectType Observable<number>
});
10 changes: 4 additions & 6 deletions src/internal/observable/defer.ts
Expand Up @@ -52,18 +52,16 @@ import { empty } from './empty';
* @name defer
* @owner Observable
*/
export function defer<O extends ObservableInput<any>>(observableFactory: () => O): Observable<ObservedValueOf<O>>;
export function defer(observableFactory: () => void): Observable<never>;
export function defer<O extends ObservableInput<any>>(observableFactory: () => O | void): Observable<ObservedValueOf<O>> {
return new Observable<ObservedValueOf<O>>(subscriber => {
let input: O | void;
export function defer<R extends ObservableInput<any> | void>(observableFactory: () => R): Observable<ObservedValueOf<R>> {
return new Observable<ObservedValueOf<R>>(subscriber => {
let input: R | void;
try {
input = observableFactory();
} catch (err) {
subscriber.error(err);
return undefined;
}
const source = input ? from(input) : empty();
const source = input ? from(input as ObservableInput<ObservedValueOf<R>>) : empty();
return source.subscribe(subscriber);
});
}

0 comments on commit 40a2209

Please sign in to comment.