Here is an interesting concept I would like to discuss: I am looking to define a function that takes an RxJs Observable provided by a service as the first argument, along with an OnNext function handler that will be passed to the subscribe method.
import { Observable } from 'rxjs';
export interface OnNextHandler<T> {
(value: T): void
}
export interface ServiceSubscriber<T> {
(providedObservable: Observable<T>, onNext: OnNextHandler<T>): void
}
The code above appears to be functioning properly, but TypeScript does not always catch errors in some cases (which I would like it to do). For example:
@Component({
selector: 'app-notes-list',
templateUrl: './notes-list.component.html',
styleUrls: ['./notes-list.component.scss']
})
export class NotesListComponent implements OnInit, OnDestroy {
activeNotes: Note[] = [];
archivedNotes: Note[] = [];
private destroy$: Subject<boolean> = new Subject<boolean>();
constructor(
private notesService: NotesService
) { }
ngOnInit() {
const { active, archived } = this.notesService; // pull our observables from the service
this.subscribeTo(active, activeNotes => this.activeNotes = activeNotes);
this.subscribeTo(archived, archivedNotes => this.archivedNotes = archivedNotes);
}
ngOnDestroy(): void {
this.destroy$.next(true);
this.destroy$.unsubscribe();
}
private subscribeTo: ServiceSubscriber<Note[]> = (providedObservable$, onNext) => {
providedObservable$
.pipe(takeUntil(this.destroy$))
.subscribe(onNext)
}
}
This Angular component is where I attempt to type the subscribeTo
method using my ServiceSubscriber
interface. The first argument is validated: for instance, if we pass a string instead of the expected Observable
, an error is thrown. However, the second argument (onNext callback) can receive any function as its value (and ideally, it should only accept functions that take an argument of type T
and return nothing).
To illustrate, if I modify the code inside ngOnInit
like so:
ngOnInit() {
const { active, archived } = this.notesService;
this.subscribeTo(active, activeNotes => activeNotes); // pay attention here on the 2nd arg
this.subscribeTo(archived, archivedNotes => archivedNotes); // and here as well
}
Now the callbacks are returning values instead of nothing as expected. What am I overlooking here, and how can I generate an error when the callback function signature is incorrect? Thank you.