Typescript Error: TS2314: Generic type 'ElementRef<T, any>' requires 2 type argument(s)

Typescript Error: TS2314: Generic type 'ElementRef<T, any>' requires 2 type argument(s)

我使用的是 Angular 5.x 模板,但我使用 https://update.angular.io/ 指南将其升级到 Angular 6。 现在我的构造函数中有这个错误

Typescript Error: TS2314: Generic type 'ElementRef<T, any>' requires 2 type argument(s)

我的代码:

import { Component, Input, Output, EventEmitter, ElementRef, HostListener }          from '@angular/core';

@Component({
  selector: 'sidebar',
  templateUrl: './sidebar.component.html'
})

export class SidebarComponent {

    @HostListener('document:click', ['$event'])
  clickout(event) {
    if(!this.eRef.nativeElement.contains(event.target)) {
          this.hideMobileSidebar.emit(true);
    }
  }

  constructor(private eRef: ElementRef) {
  }

...

我在之前的 Angular 版本 5 中没有这个错误。

发生了什么变化?我不明白文档:( https://angular.io/api/core/ElementRef

他们已将 nativeElement 属性 从 any 更改为 generic type

如果您想要快速修复,请将 eRef: ElementRef 更改为 eRef: ElementRef<any>,这与之前的版本相同。

此更改意味着您现在可以为被引用的 DOM 元素定义 class 类型。这将有助于 TypeScript 编译以强制执行该类型,以及 IDE 自动完成功能。

有许多不同的 class 类型,但以基本 class Element is used for most DOM elements. If you know it's going to be a <input> element you can use HTMLInputElement 为例。

在您的示例中,组件正在为构造函数注入它的 DOM 元素。这将是一个通用的 HTMLElement。所以代码会像这样更新:

constructor(private eRef: ElementRef<HTMLElement>) {
     const title = eRef.nativeRef.title;
     // ^^^ the above title property is now verified by TypeScript at compile-time
}

我解决了这个问题。

我做的只是运行npm i @angular-cli --save,从6.0.7版本变成了6.0.8,我也全局更新了。然后我 运行 ng update @angular/cli 但它并没有改变我的 package.json 中的任何内容。现在我可以单独使用 ElementRef,或 ElementRef<HTMLElement>ElementRef<HTMLElement, any>,现在一切正常。我不明白 angular-cli 与我的 tslint 或 typescript 安装有什么关系,但这是我唯一做的事情。