user2866746 user2866746 - 5 months ago 53
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

.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


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 :