rxjs icon indicating copy to clipboard operation
rxjs copied to clipboard

Documentation on void Subjects is incorrect

Open TrevorKarjanis opened this issue 3 years ago • 3 comments

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

TrevorKarjanis avatar Jun 27 '22 14:06 TrevorKarjanis

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; //This will be proper syntax.

Ex. If user want to emits string from subject const subject = new Subject(); setTimeout(() => subject.next('dummy'), 100);

and if user wants to emits number from subject const subject = new Subject(); setTimeout(() => subject.next(5), 5000);

Vrt0304 avatar Aug 02 '22 06:08 Vrt0304

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

TrevorKarjanis avatar Aug 05 '22 14:08 TrevorKarjanis

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.

Vrt0304 avatar Aug 05 '22 15:08 Vrt0304