user2866746 user2866746 - 1 year ago 119
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

Answer Source

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 :

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download