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

a 夏天 提交于 2019-12-10 06:15:21

问题


I'm using an Angular 5.x template, but I upgrade it to Angular 6 using https://update.angular.io/ guide. Now I have this error in my constructor

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

My Code:

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) {
  }

...

I don't have this error in previous Angular version 5.

What was the change? I don't understand the docs :( https://angular.io/api/core/ElementRef


回答1:


They've changed the nativeElement property from any to a generic type.

If you want the quickly fix, then change eRef: ElementRef to eRef: ElementRef<any> which is the same as in previous versions.

This change means you can now define the class type for the DOM element that is being referenced. This will assist in TypeScript compiling to enforce that type, and also IDE auto-complete features.

There are many different class types, but the base class Element is used for most DOM elements. If you know it's going to be a <input> element you can use HTMLInputElement as an example.

In your example the component is injecting it's DOM element for the constructor. Which would be a generic HTMLElement. So the code would be updated like this:

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



回答2:


I fix the problem.

What I did was just run npm i @angular-cli --save and it changed from version 6.0.7 to 6.0.8, I also updated it globally. Then I run ng update @angular/cli but it doesn't change anything in my package.json. Now I can use ElementRef alone, or ElementRef<HTMLElement> or ElementRef<HTMLElement, any>, EVERYTHING WORKS NOW. I don't understand what angular-cli has to do with my tslint or typescript install, but thats the only thing I did.



来源:https://stackoverflow.com/questions/50704880/typescript-error-ts2314-generic-type-elementreft-any-requires-2-type-argu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!