组合错误最新和严格的键入 - "No overload matches this call."



最近将一个项目从Angular v9更新为v11。选择了严格的打字,当然也犯了很多错误,在这一点上被难住了。

使用combineLatest从3个可观察器(每个都是一个firebase doc.valueChanges((或collection.valueChanges((((生成发布

我的代码:

getEdition(editionId: string): AngularFirestoreDocument<Edition> {
return this.afs.collection('editions').doc(editionId);
}
const editionRef: Observable<Edition | undefined> = this.editionService.getEdition(ed.id).valueChanges();
combineLatest([editionRef, sectionsRef, articlesRef]).subscribe(([edition, sections, articles]: [Edition, Section[], Article[]]) => {
// do stuff, returns void
});

版本:

import { Moment } from 'moment';
export interface Edition {
id: string;
pubTypeId: string;
date: string | Moment;
imgCaption: string;
imgCredit: string;
imgLink: string;
imgSrc: string;
introText: string;
hasPreface: boolean;
preface: string;
printLink: string;
}

我的错误:

error TS2769: No overload matches this call.
Overload 1 of 5, '(observer?: NextObserver<[Edition | undefined, DocumentData, DocumentData]> | ErrorObserver<[Edition | undefined, DocumentData, DocumentData]> | CompletionObserver<...> | undefined): Subscription', gave the following error.
Argument of type '([edition, sections, articles]: [Edition, Section[], Article[]]) => void' is not assignable to parameter of type 'NextObserver<[Edition | undefined, DocumentData, DocumentData]> | ErrorObserver<[Edition | undefined, DocumentData, D
ocumentData]> | CompletionObserver<...> | undefined'.
Property 'complete' is missing in type '([edition, sections, articles]: [Edition, Section[], Article[]]) => void' but required in type 'CompletionObserver<[Edition | undefined, DocumentData, DocumentData]>'.
Overload 2 of 5, '(next?: ((value: [Edition | undefined, DocumentData, DocumentData]) => void) | undefined, error?: ((error: any) => void) | undefined, complete?: (() => void) | undefined): Subscription', gave the following error.
Argument of type '([edition, sections, articles]: [Edition, Section[], Article[]]) => void' is not assignable to parameter of type '(value: [Edition | undefined, DocumentData, DocumentData]) => void'.
Types of parameters '__0' and 'value' are incompatible.
Type '[Edition | undefined, DocumentData, DocumentData]' is not assignable to type '[Edition, Section[], Article[]]'.
Type 'Edition | undefined' is not assignable to type 'Edition'.
Type 'undefined' is not assignable to type 'Edition'.

我知道我需要以某种方式调整我的打字方式,但不太确定该怎么办,因为我正在使用combine最新消息。。。

我的猜测是,在editionRef -> edition -> Edition链的某个地方,您有一个隐含的any类型。来自文档:

用null或初始化的任何变量、参数或属性undefined将具有any类型,即使启用了严格的null检查。

因此,我将首先尝试在该链中找到一个未初始化的undefinednull变量。

错误

类型"undefined"不可分配给类型"Edition"。

表示不应允许this.editionService.getEdition(ed.id).valueChanges()返回undefined,Observable的类型应仅为Edition

最后,在修复中,最好实际指示需要强制执行的类型。

您可以使用as对类型进行类型转换,但您正在将不确定的内容更改为需要的内容。这个选项可能会起作用,但不起作用;强制执行";按照打字的方式打字。

因此,正如你在评论中所说,最好的解决方案是:

subscribe(([edition, sections, articles]: [Edition | undefined, Section[], Article[]]) => { ... }

最新更新