Currently, I am developing an Angular application that utilizes Firebase Firestore database through the angularfire2 library. However, I am encountering a challenge.
I must admit that my background is more in Java than TypeScript, so there might be some gaps in my understanding of this topic.
The issue revolves around a method like the one shown below:
fetchCompletedOrCancelledExercise() {
//return this.exercises.slice();
this.db
.collection('finishedExercises')
.valueChanges()
.subscribe((exercises: Exercise[]) => {
this.finishedExercisesChanged.next(exercises);
});
}
This method essentially retrieves an array of Exercise objects whenever a change occurs on Firestore and emits this array as an event through a Subject.
However, both my IDE and console display an error in relation to the line exercises: Exercise[] within the arrow function parameter. The error message reads as follows:
No overload matches this call.
Overload 1 of 3, '(observer?: Partial<Observer<unknown[]>> | undefined): Subscription', gave the following error.
Type '(exercises: Exercise[]) => void' has no properties in common with type 'Partial<Observer<unknown[]>>'.
Overload 2 of 3, '(next: (value: unknown[]) => void): Subscription', gave the following error.
Argument of type '(exercises: Exercise[]) => void' is not assignable to parameter of type '(value: unknown[]) => void'.
Types of parameters 'exercises' and 'value' are incompatible.
Type 'unknown[]' is not assignable to type 'Exercise[]'.
Upon reviewing the error, it seems that the problem lies in the type declared for .valueChanges() which returns Partial<Observer<unknown[]>> | undefined. This prompted me to modify my method by removing the type:
fetchCompletedOrCancelledExercise() {
//return this.exercises.slice();
this.db
.collection('finishedExercises')
.valueChanges()
//.subscribe((exercises: Exercise[]) => {
.subscribe((exercises) => {
this.finishedExercisesChanged.next(exercises);
});
}
With this adjustment, the method functions as expected.
What perplexes me is that the tutorial I am following employs this specific type. An alternative solution was to disable TypeScript strict mode.
Upon reflection, I suspect that the root of the issue lies in the fact that .valueChanges() returns Observable<unknown[]>, an Observable containing a generic array of unspecified type. Consequently, when strict mode is enabled, the automatic casting of elements from this array into my Exercise model object becomes problematic. Does this reasoning sound accurate?
This leads me to another question: how crucial is strict mode in this scenario? Would it be more beneficial to disable strict mode but maintain the ability to specify the type?