I am working with TypeScript and React. In my component, which is a dialog window, I want to store the trigger element, such as a button as a property. When the component unmounts, I want to return focus to that element. However, I am receiving an error from TSLint that I am not sure how to resolve.
class Dialog extends React.Component<Props, {}> {
...
focusedElementBeforeDialogOpened: HTMLInputElement;
componentDidMount() {
this.focusedElementBeforeDialogOpened = document.activeElement;
...
}
...
}
I am receiving the error on the line where I am assigning the property value:
[ts] Type 'Element' is not assignable to type 'HTMLInputElement'.
Property 'accept' is missing in type 'Element'.
However, if I change the type of the property to Element or even HTMLInputElement I receive an error in componentWillUnmount()
componentWillUnmount() {
...
this.focusedElementBeforeDialogOpened.focus();
}
This error is in regards to Element type not having the focus() method.
Question
Is there a way to tell TypeScript that document.activeElement should be an input type? Something like
this.focusedElementBeforeDialogOpened = <HTMLInputElement>document.activeElement;
Or is there a better way around this so declare the type that supports both document.activeElement and .focus()?