DEV Community

Pavel M
Pavel M

Posted on

TypeScript ValidityState

const input: HTMLElement = e.target
const validity: ValidityState = input.validity
setValidity(validity.valid)
Enter fullscreen mode Exit fullscreen mode

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?

Top comments (3)

Collapse
 
harry0000 profile image
harry

HTMLElement does not have readonly validity: ValidityState property. Only the following elements have that property.

github.com/microsoft/TypeScript/bl...

  • HTMLButtonElement
  • HTMLFieldSetElement
  • HTMLInputElement
  • HTMLObjectElement
  • HTMLOutputElement
  • HTMLSelectElement
  • HTMLTextAreaElement

If you are using React, you can write as follows:

TS playground link

const input: React.FC = () => {
    return (
        <input onChange={(e) => {
          const input: HTMLInputElement = e.target
          const validity: ValidityState = input.validity
          setValidity(validity.valid)
        }}/>
    )
}
Enter fullscreen mode Exit fullscreen mode

or

const input: React.FC = () => {
    return (
        <input onChange={(e) => {
          // e: React.ChangeEvent<HTMLInputElement>
          setValidity(e.target.validity.valid)
        }}/>
    )
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
harry0000 profile image
harry

Or if you wanted to define a handler function, you can write as follows:

const handler: (e: React.ChangeEvent<HTMLInputElement>) => void = (e) => {
    // ...
}
Enter fullscreen mode Exit fullscreen mode

or

const handler = (e: React.ChangeEvent<HTMLInputElement>): void => {
    // ...
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
vkrms profile image
Pavel M

Thanks a bunch! It helped a lot.