rxjs
rxjs copied to clipboard
Documentation on void Subjects is incorrect
Describe the bug
The documentation states that new Subject() is an alias for new Subject<void>(). However, with TypeScript ~4.3.5 new Subject() is an alias for new Subject<unknown>(), and subject.next requires an argument.
Expected behavior
If the solution is to update the documentation, then the following:
import { Subject } from 'rxjs';
const subject = new Subject<void>();
subject.subscribe({
next: () => console.log('One second has passed'),
});
setTimeout(() => subject.next(), 1000);
Reproduction code
import { Subject } from 'rxjs';
const subject$ = new Subject();
subject$.next();
const void$ = new Subject<void>();
void$.next();
Reproduction URL
https://stackblitz.com/edit/rxjs-adkqeh?devtoolsheight=60&file=index.ts
Version
7.5.5
Environment
TypeScript 4.3.5
Additional context
No response
as following syntax, const subject = new Subject(); //without void will incorrect in terms of type safety for subject emitter and developer might return any data type from subject and will cause error. so it will mislead by this syntax.
To maintain type safety I would suggest
const subject = new Subject
Ex.
If user want to emits string from subject
const subject = new Subject
and if user wants to emits number from subject
const subject = new Subject
At least as demonstrated on StackBlitz, the subject type doesn't change based on what's provided to Subject.next. It still requires declaring the generic, e.g. new Subject<string>();
https://stackblitz.com/edit/rxjs-adkqeh?devtoolsheight=60&file=index.ts
above example should get correct as follow, If user want to emits string from subject
const subject = new Subject<string>();
setTimeout(() => subject.next('dummy'), 100);
and if user wants to emits number from subject
const subject = new Subject<number>();
setTimeout(() => subject.next(5), 5000);
To maintain type safety I would suggest
const subject = new Subject<void>(); //This will be proper syntax.