Picci
Picci

Reputation: 17762

Typescript: adding type definition to Observable.of(null)

In my program I have a method that can return either an observable of MyClass or Observable.of(null). The code is along the following lines:

doSomething(someParams) {    
      return this.backEnd.getStuff(someParams)
                    .switchMap(data => {
                        if (!data ) {
                            return Observable.of(null);
                        } else {
                            this.doSomethingElse(data);
                        }
                    });
}

where doSomethingElse() returns an Observable<MyClass>.

If I code the method as above, I loose intellisense since my IDE (VSCode) tells me that the method doSomething() returns an Observable.

Is there a way to maintain intellisense in such a case? What I would like to have is the IDE suggesting me that the method doSomething() returns an Observable<MyClass> and naturally have my logic check is there is actually an instance of MyClass or null when the result is subscribed.

Upvotes: 0

Views: 75

Answers (1)

Saravana
Saravana

Reputation: 40614

You can type your return type as Observable<MyClass | null> where MyClass | null is a union type:

doSomething(someParams): Observable<MyClass | null> {
   // ...
}

Upvotes: 1

Related Questions