feat(ElementRef): provide option to make generic
See original GitHub issueI’m submitting a … (check one with “x”)
[x] feature request
Current behavior
If I want to get a hold of a Custom Element by assigning an ElementRef via @ViewChild, the nativeElement property is typed as any instead of the Custom Element type.
@Component({
template: `
<my-element #my-element></my-element>
`
})
class MyComponent {
@ViewChild('my-element') myElement:ElementRef;
ngAfterViewInit() {
this.myElement.nativeElement; // type is "any"
}
}
Expected behavior
@ViewChild('my-element') myElement:ElementRef<MyElement>;
Since TypeScript doesn’t support default generic types (see discussion, ElementRef would require a type be provided every time it’s used as a type annotation. Since this would be a breaking change, I propose subclassing ElementRef as CustomElementRef, and typing the nativeElement property as the generic type.
@ViewChild('my-element') myElement:CustomElementRef<MyElement>;
What is the motivation / use case for changing the behavior?
So that type information can be available when using custom elements (code completion, refactoring, all the usual goodies).
- Language: [all | TypeScript X.X | ES6/7 | ES5]
TypeScript
CC @robdodson
Issue Analytics
- State:
- Created 7 years ago
- Reactions:13
- Comments:8 (4 by maintainers)

Top Related StackOverflow Question
Note: there are many workarounds to get type information without having a generic
ElementRef; they’re just a little verbose.ElementRefinterface:nativeElementinline when accessingI’m 👎 on
T extends HTMLElementbecauseElementRefis not a thing only of browser.