0
votes

Why does returning interval(500) throw the following type error in the code below?

const source = timer(0, 5000);
const example = source.pipe(switchMap(() => interval(500)));
const subscribe = example.subscribe(val => console.log(val));

StackBlits

Argument of type 'UnaryFunction<Observable<number>, Observable<number>>' is not assignable to parameter of type 'OperatorFunction'.

Types of parameters 'source' and 'source' are incompatible.

Type 'Observable<any>' is not assignable to type 'Observable<number>'.

Property 'source' is protected but type 'Observable<T>' is not a class derived from 'Observable<T>'.

This is the from the first switchMap example found on learnrxjs.io.

1
I think it is a problem in the configuration of the stackblitz you use. Try this stackblitz.com/edit/typescript-bbrzza and you should not see the issue any more - Picci

1 Answers

1
votes

The issue is that timer is defined to emit number values. So, source will also assume number values will be emitted. However, switchMap makes no assumptions about what type will be emitted by the returned observable (hence the any). This means that your source goes from emitting numbers to emitting anything at all.

A simple solution is this

import { timer, interval } from 'rxjs';
import { switchMap } from 'rxjs/operators';

//emit immediately, then every 5s
const source = <any>timer(0, 5000); //Here, we say that source can emit anything
//switch to new inner observable when source emits, emit items that are emitted
const example = source.pipe(switchMap(() => interval(500)));
//output: 0,1,2,3,4,5,6,7,8,9...0,1,2,3,4,5,6,7,8
const subscribe = example.subscribe(val => console.log(val));