Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(defer): restrict allowed factory types #4835

Merged
merged 3 commits into from Jun 6, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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);
});
}