最近将一个项目从 Angular v9 更新到 v11。选择了严格的打字方式,当然遇到了无数错误,难倒在这个错误上。
使用 combineLatest 从 3 个 observable 生成发布(每个都是 firebase doc.valueChanges() 或 collection.valueChanges())
我的代码:
struct BlockWatchApp: App {
@WKExtensionDelegateAdaptor(ExtensionDelegate.self) var extensionDelegate
var body: some Scene {
WindowGroup {
NavigationView {
WatchView()
}
}
}
Edition.ts:
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;
}
我知道我需要以某种方式调整我的输入,但我不确定该怎么做,因为我在这里使用 combineLatest ......
答案 0 :(得分:1)
我的猜测是,在 editionRef -> edition -> Edition
链的某个地方,您有一个隐式 any
类型。来自文档:
任何以 null 或 undefined 将具有任何类型,即使打开了严格的空检查。
因此,我会首先尝试在该链中查找未初始化的 undefined
或 null
变量。
错误
<块引用>类型 'undefined' 不能分配给类型 'Edition'。
表示永远不应该允许this.editionService.getEdition(ed.id).valueChanges()
返回undefined
,并且Observable的类型只能是Edition
。
最后,在您的修复中,最好实际指明需要强制执行的类型。
您可以我们as
对类型进行类型转换,但是您正在将不确定的内容更改为您需要的内容。此选项可能会起作用,但不会像打字那样“强制”打字。
因此,正如您在评论中所说的那样,最佳解决方案是:
subscribe(([edition, sections, articles]: [Edition | undefined, Section[], Article[]]) => { ... }