4

I'm building a typescript angular 2 app and using rxjs. I am following the example here:

https://angular.io/docs/ts/latest/tutorial/toh-pt6.html#!#stq=formgroup&stp=1

All though I am trying to strongly type my return signatures with typescript. This may be my problem in that you aren't supposed to. But it seems like you should be able to.

Suppose I have service that is typed to return an Observable>.

 public search(term: string) : Observable<Array<MyModel>> { // http call }

In my component I am attempting to listen to this observable stream and return the results.

 private search = new Subject<Search>();
 results: Observable<Array<MyModel>>;

 ngOnInit() {
     this.results = this.search
        .debounceTime(400)
        .distinctUntilChanged()
        .switchMap(search => {
            return service.search(search.term); // returns Observable<Array<MyModel>>
        });
  }

This doesn't compile with the message Cannot convert type Observable<Object> to type Observable<MyModel[]>>

I don't understand why switchmap is returning an Observable instead of my type. Do I need to map it again before giving it to results? Is this a typescript typings issue with the return signature of switchmap?

2
  • 2
    I think you just need a cast. Commented Aug 11, 2016 at 14:03
  • I had tried that but ignorantly casted the return statement instead of on the end of the switchmap chain which is where the cast belongs. That was a boneheaded thing to miss. Thanks! Commented Aug 11, 2016 at 16:03

2 Answers 2

2

Typescript might have wrong type inference, I would try one of the following:

give your handler a return type:

.switchMap((search): Observable<Array<MyModel>> => {
        return service.search(search.term); // returns Observable<Array<MyModel>>
    });

and if this doesn't work, "compromise" for changing the type of the results variable to:

 results: Observable<any>;
Sign up to request clarification or add additional context in comments.

Comments

0

The error message is actually right. However, it's unclear what line caused the error without a stack trace.

In the ngOnInit() method you call:

this.results = this.search
    .debounceTime(..)
    ...

This chain of operators always returns an Observable which is not as the result property expects (Observable<Array<MyModel>>) because the Subject's generic is Search.

Operator switchmap() returns always an Observable. Its return type has nothing to do with the callable.

You should be able to solve this by simply typecasting the result:

this.results = Observable<MyModel[]>this.search
    .debounceTime(..)
    ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.