Imagine having this method within a Typescript/Angular project:
subscribeSubject() {
const subject = new Subject();
subject.subscribe({
next: (v1: number) => console.log('v1=',v1)
});
subject.subscribe({
next: (v2: number) => console.log('v2=',v2)
});
const observable = from([1,2,3]);
observable.subscribe(subject);
}
In Typescript, I defined the arguments for the above observers' next methods as strings. However, the observable I generated emits numbers instead. Curiously, when I tested it out, the observers printed whatever values I emitted (I changed the numbers to characters 'a', 'b', and 'c' and it displayed v1=a v2=a v1=b v2=b v1=c v2=c
).
It dawned on me why this behavior occurred. TypeScript simply overlooks the type discrepancies and interprets the code as plain Javascript, where the strict typing is disregarded. Thus, it doesn't enforce any mismatch in types between emitters and receivers.
This led me to ponder why TypeScript allows such behavior. This raises my inquiry: does TypeScript struggle to anticipate when numbers will be sent to functions expecting strings? How could it possibly predict that? While I create an observable emitting numbers, the compiler cannot foresee how they will be utilized. It's plausible that I might redirect them to different subjects which indeed accept numbers. Although the subject eventually subscribes to the observable, at that point, TypeScript may find it too intricate to trace the data flow efficiently (particularly in complex applications), hence chooses not to intervene. Essentially, it presents an isolated problem.
Thus, my question stands: am I correct in assuming the aforementioned scenario is inherently challenging for compilers to resolve?