Øystein Amundsen
Øystein Amundsen

Reputation: 4203

Different return type depending on input

I have a small challenge with generics, can anybody help?

We have a common websocket connection where different panels in our app "subscribe" to different types of data through socket messages. methodCall below is a common method which sends a "subscribe" message through our open websocket connection and gives parameters for either one type of data or another. The two types have two very different set of properties.

I want to make the following work:

service.methodCall({type: 'oneType'}).subscribe((values: Type1Value) => { ... });
service.methodCall({type: 'anotherType'}).subscribe((values: Type2Value) => { ... });

One method returning one specific set of Observable type depending on the given parameter. What needs to to happen in the methodCall descriptor to make this happen? The following only gives me union types, which is not what I need:

methodCall(cfg: {type: 'oneType' | 'anotherType'}): Observable<Type1Value | Type2Value> {
  ...
}

It's relatively important that the cfg object which is input to methodCall remains an object and is not flattened out as arguments.

I do not want to create two methods to do this, as this would result in a lot of duplicate code.

Upvotes: 0

Views: 61

Answers (1)

Terry
Terry

Reputation: 66103

You can use function overloads to achieve what you want, assuming that one type will always return an Observable of another specific type:

methodCall(cfg: { type: 'oneType' }): Observable<Type1Value>
methodCall(cfg: { type: 'anotherType' }): Observable<Type2Value>
methodCall(cfg: { type: 'oneType' | 'anotherType' }): Observable<Type1Value | Type2Value> {
  ...
}

Upvotes: 1

Related Questions