I recently started learning rxjs within the context of Angular. After downloading a project from a tutorial, I encountered a compilation issue with one particular class. Despite my attempts to fix it by considering potential library updates, I was unsuccessful. Even after simplifying the code to its basic form, I still cannot comprehend why the error persists. The Intellij IDE is highlighting the problem through a typescript error message.
The error occurs on line 7 in the code snippet below:
import { flatMap, map } from 'rxjs/operators';
import { Observable, of } from 'rxjs';
export class TestClass {
a$ = of('dummy').pipe( // Observable<string>
flatMap(s => of(s)), // Observable<string>
map<string, string>(s => s) // Observable<string> <-- ERROR HERE
);
b$ = of('dummy').pipe( // Observable<string>
flatMap(s => of(s)), // Observable<string> or Observable<Observable<string>> ?
map<Observable<string>, Observable<string>>(os => os)
);
}
The map()
functions are included to understand the expected type following the flatMap()
.
My understanding of flatMap is that it takes an Observable<T>
, maps each item T
to another Observable<T>
, and then flattens the results back into an Observable<T>
.
However, there seems to be an issue with variable 'a$'. https://i.sstatic.net/ZGJVP.png
Surprisingly, variable 'b$' compiles without any errors. It appears that flatMap
does not flatten the content for 'b$', resulting in an
Observable<Observable<T>>
. Subsequently, the next map()
expects items of type Observable<T>
.
So what could possibly be causing this discrepancy? Have I misinterpreted something regarding flatMap()
or pipe()
? Or is there a glitch with my compiler/IDE generating misleading error messages?
Update:
In the end, the issue stemmed from typescript providing a false error message. This revelation has renewed my confidence in my grasp of functional programming concepts.