Suppose we had this method in a Typescript/Angular application:
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 can declare the arguments to the above observers' next methods as strings. But then the observable I create emits numbers; I wondered what would happen in this situation, expecting Typescript to tell me I can't emit numbers to observers that take strings. But it didn't. It let me compile it. And when I ran it, I found the observers printed whatever I emitted (I switch the numbers to chars 'a', 'b', and 'c' and it came through v1=a v2=a v1=b v2=b v1=c v2=c).
Then I realized why. Obviously, because typescript is just letting it through, it becomes plain old vanilla Javascript in which the type is simply dropped. So it doesn't care what types of values it gets, it will print them.
Then I wondered why Typescript would allow this. That's where my question comes in. Is the above situation one in which Typescript can't determine that numbers will be emitted to methods that take strings? How could it tell? Yes, I'm creating an observable that emits numbers, but at that specific line, the compiler can't tell how I'm going to use it. I might just emit them to different subjects, ones that do take numbers. And yes, the subject does eventually subscribe to the observable, but at this point, I wonder if that's too complicated a trail for the Typescript to be following (I can see it turning into a deep rabit hole in some complicated applications), and so it just doesn't. After all, the line observable.subscribe(subject) doesn't have to come right after const observable = from(['a','b','c']). It could be anywhere in the application. In short, it's an isoluable problem.
So my question is: have I got the above right? Is this problem insoluable to compilers?
![const observable = from(['a', 'b']);
observable.subscribe(subject);](https://i.stack.imgur.com/XvZkU.png)