When using document.activeElement.blur() the compiler tells me that the property does not exist.
.blur()
is only guaranteed to exist on HTMLElements, not all Elements. I have frequently seen exceptions caused by unguarded document.activeElement.blur()
, because document.activeElement was an SVG element rather than HTML.
@svanuden If you're sure you want to use that, you may use it like:
(document.activeElement as HTMLElement).blur();
Though I'll suggest to still wrap it in a try-catch block.
@bharatramnani94 Running into a very similar issue and tried your (document.activeElement as HTMLElement)
but I'm trying to call the type
property. Its use case is determining if the user has a text input focused so that keyboard shortcuts within an app don't fire. Both of the below lines of code still make VSCode highlight "type" red and say that the type property does not exist on HTMLElement
:
const elementType = (document.activeElement as HTMLElement).type;
const element = <HTMLElement>document.activeElement;
if ( element.type === 'text' ) {}
Of course you can still use it and it works in the console but it seems like there should be a way to fix it. The MDN Docs for it say it returns an Element which according to other TS issues I've found says that we should likely be casting it as an HTMLElement
.
Update: I have found that casting this as an HTMLInputElement
does get the "error" to go away. That seems wrong since an input is not always the focus, if you aren't clicked anywhere in particular then the <body>
is likely to be the active element.
const elementType = (document.activeElement as HTMLInputElement).type;
Update 2: Upon reading some more on MDN / Stack Overflow it looks like HTMLInputElement
inherits from HTMLElement
and that class is what has the properties such as type
and `value.
This StackOverflow answer helped as well.
Save solution might be to check if document.activeElement
is of type HTMLElement
:
if (document.activeElement instanceof HTMLElement) {
document.activeElement.blur();
}
Then you don't need try/catch block, because you ensured that your element has blur
method. No cast needed to satisfy TypeScript.
I am trying to pass a ref property into a custom FieldInput component where I use Input from Native Base.
const fieldRef = useRef<Input>(null);
...
fieldRef.current?.blur();
I get the same error here: Property 'blur' does not exist on type 'Input'.
How can I resolve it in this case? @tischsoic @bharatramnani94
https://stackoverflow.com/questions/63757905/property-blur-does-not-exist-on-type-input
Most helpful comment
Save solution might be to check if
document.activeElement
is of typeHTMLElement
:Then you don't need try/catch block, because you ensured that your element has
blur
method. No cast needed to satisfy TypeScript.