DEV Community

Pavel M
Pavel M

Posted on

3 2

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.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay