How can we constrain the return type of getStreamFor$(item: Item)
based on the parameter type Item
?
The desired outcome is:
- When calling
getStream$(Item.Car)
, the type ofstream$
should beObservable<CarModel>
- When calling
getStream$(Item.Animal)
, the type ofstream$
should beObservable<AnimalModel>
Currently, the type of stream$
is
Observable<CarModel | AnimalModel | TemperatureModel>
.
(refer to the 'HERE' comment in this StackBlitz)
enum Item {
CAR = 'car',
ANIMAL = 'animal',
TEMPERATURE = 'temperature'
}
interface CarModel {
make: string;
}
interface AnimalModel {
breed: string;
}
interface TemperatureModel {
tmp: number;
scale: string;
}
class Channel {
stream: {
[prop in Item]: Observable<CarModel | AnimalModel | TemperatureModel>
};
constructor() {
this.stream = {
[Item.CAR]: of({ make: 'Ford' }) as Observable<CarModel>,
[Item.ANIMAL]: of({ breed: 'Cat' }) as Observable<AnimalModel>,
[Item.TEMPERATURE]: of({ tmp: 35, scale: 'Celsius' }) as Observable<TemperatureModel>
};
}
getStreamFor$(item: Item): Observable<CarModel | AnimalModel | TemperatureModel> {
return this.stream[item];
}
}
const c = new Channel();
const stream$ = c.getStreamFor$(Item.CAR) // <--- HERE
.pipe(
map((value) => {
value.make // <--- '.make' is marked as error by IDE
}),
)