const input: HTMLElement = e.target
const validity: ValidityState = input.validity
setValidity(validity.valid)
I'm just getting into typescript and having a problem with the ValidityState API: the second line gets a red squiggly underline with Unsafe assignment of an 'any' value
.
What's the proper course of action here?
Discussion (5)
HTMLElement
does not havereadonly validity: ValidityState
property. Only the following elements have that property.github.com/microsoft/TypeScript/bl...
If you are using React, you can write as follows:
TS playground link
or
Or if you wanted to define a handler function, you can write as follows:
or
You can also use
ChangeEventHandler
:Tho generally, if you inline the handler, you don't need to type it because the type is inferred automatically.
A few recommendations that might help:
currentTarget
instead oftarget
. Thetarget
property ofEvent
points to the element that triggered the event, butcurrentTarget
points to the element that has the event listener, which is almost always what you actually want.You could also simplify it quite a bit if you only need the
validity.valid
value:event
typed so the type ofcurrentTarget
andtarget
are inferred. In React that's done for you with the*EventHandler
types, with Angular you have other solutions, but it depends on what you're using.Hope that helps a little.
Cheers!
Thanks a bunch! It helped a lot.