TS2564 属性 mapViewEl 没有初始值设定项

Rad*_*ghe 5 arcmap typescript angular

我正在努力获取适用于 Angular (v4) 的 ArcMap Javascript,以在 Angular (v10) 项目中显示地图。我发现的所有代码示例(此处ESRI 官方此处、stackblitz此处)都非常相似。viewChild 是这样创建的:

export class EsriMapComponent implements OnInit, OnDestroy {
@ViewChild("mapViewNode", { static: true }) private mapViewEl: ElementRef;
view: any;
constructor() { }
Run Code Online (Sandbox Code Playgroud)

但我的 IDE 告诉我TS2564 Property mapViewEl has no initializer and is not definitely assigned in the constructor

我可以将此行更改为:

@ViewChild("mapViewNode", { static: true }) private mapViewEl!: ElementRef;
Run Code Online (Sandbox Code Playgroud)

地图已绘制,但我不喜欢删除 Typescript 保护,特别是因为我在网上找到的任何工作示例都没有这样做。

esri-map.component.html 非常简单:<div #mapViewNode></div>

如何修复 TS2564 错误?

Rob*_*rto 2

我的建议是使用可选运算符 ( ?) 而不是非空断言 ( !)。因为属性实际上是undefined在组件渲染之前存在的,所以最终您需要管理undefined属性中的潜在值。此外,如果组件名称@ViewChild('compName')不正确,undefined如果将其标记为可选,则属性也会如此,这听起来比not-null替代方案更现实。

@ViewChild("mapViewNode", { static: true }) private mapViewEl?: ElementRef;
Run Code Online (Sandbox Code Playgroud)