我正在通过angularfire2库使用Firestore数据库开发一个有角度的应用程序,我有以下问题。
我说我不太喜欢TypeScript (我来自Java),可能在这个话题上我有一些缺失的知识。
基本上我有这样的方法:
fetchCompletedOrCancelledExercise() {
//return this.exercises.slice();
this.db
.collection('finishedExercises')
.valueChanges()
.subscribe((exercises: Exercise[]) => {
this.finishedExercisesChanged.next(exercises);
});
}从根本上说,它是检索练习对象数组时,为了通过主题将该数组作为事件而在Firestore上进行更改。
IDE (但当它试图编译时也是控制台)给我一个错误的代码练习: Exercise[] (箭头函数param)。错误是:
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[]'.读取错误并检查.valueChanges()方法返回的内容(这是:Partial> 未定义)问题似乎是在“我的订阅”()中声明的Exercise[]类型。
因此,以这种方式更改我的方法(移除类型):
fetchCompletedOrCancelledExercise() {
//return this.exercises.slice();
this.db
.collection('finishedExercises')
.valueChanges()
//.subscribe((exercises: Exercise[]) => {
.subscribe((exercises) => {
this.finishedExercisesChanged.next(exercises);
});
}效果很好。
我不明白的是,在我所遵循的教程中,它使用了这种类型。
另一个解决方案是禁用TypeScript严格模式。
基本上,我怀疑问题在于我的.valueChanges()返回Observable,一个可观察的包含未指定类型的泛型数组)。因此,如果启用了严格模式,它就不能自动将这个数组的元素转换到我的练习模型对象中。我的推理正确吗?
如果这让我想到另一个问题:这个严格的模式有那么重要吗?或者在这种情况下更重要的是禁用严格模式,但允许指定类型?
发布于 2022-08-02 17:08:15
这与打字稿的推断类型机制有关。
你试过吗?
fetchCompletedOrCancelledExercise() {
this.db
.collection<Exercise[]>('finishedExercises')
.valueChanges()
.subscribe((exercises) => {
this.finishedExercisesChanged.next(exercises);
});}
所以打字本会知道你的练习是Exercise[]
https://stackoverflow.com/questions/73211078
复制相似问题