Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RXJS 'never' subject as the generic type

I am working with RXJS and Typescript in an angular project. I have written the following in my code:

const sub = new Subject<never>();

I expect this line to mean that any subscriber that defines the 'next' and 'error' methods, as can be seen below, will never have the 'next' method called. Only the 'error' method will be called, if at all.

sub.subscribe(() => /*do something with 'next' value*/, error => /*do something with 'error' value*/)

However, when I write the following:

sub.next();

I do not get a compilation error.

From my understanding the Subject generic is the type returned by the subject, so never means that we never call the next method.

Can anyone explain why? Is this a bug, a feature or misunderstanding on my part?

like image 457
Noy Oliel Avatar asked Oct 26 '25 11:10

Noy Oliel


2 Answers

Specifying the type param on your Subject does restrict the type of value that you can pass when you call .next(), so if you attempt to pass a value: sub.next('string value') you will get an error:

Argument of type 'string' is not assignable to parameter of type 'never'.(2345)

However, the value parameter of Subject.next() is optional (in RxJS v6). This means, calling sub.next() without passing argument is allowed, so you can call Subject.next with both an argument of type T or with no argument at all.


I believe this behavior has changed in RxJS v7. Interesting GitHub Issue

like image 142
BizzyBob Avatar answered Oct 29 '25 00:10

BizzyBob


It looks like for Subject<T> the next method is defined like this: next(val: T | undefined): void, so you can always pass undefined into it. This is different to BehaviorSubject for example, where the signature is next(val: T): void and trying to call next will produce a compile-time error.

I'm not sure why this is the case.

like image 27
Mike Jerred Avatar answered Oct 29 '25 00:10

Mike Jerred



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!