user2866746 user2866746 - 12 days ago 6
TypeScript Question

Subscrible to Observable in TypeScript method with multiple possible return type

I have a TS method defined with the signature

getById(id: string): Observable<IResponseMessage> | Observable<IStrategy> {
}


But when I'm trying to subscribe the above method like this

this.strategyService.getById(id)
.subscribe(success => {

});


The compile time error occur that says
Cannot invoke an expression whose type lacks a call signature.


I don't know how to subscribe to method with multiple possible return type. Please suggest

Answer

getById(id: string): Observable | Observable {

I would make it

getById(id: string): Observable<IResponseMessage | IStrategy> {

Then you get the same subscribe and you discriminate inside the subscribe between ResposneMessage and Strategy using type guards : https://basarat.gitbooks.io/typescript/content/docs/types/typeGuard.html

Comments