Typesafe event handlers with Preact + Typescript
Asked Answered
D

1

7

I am writing a simple component with Preact that uses an onChange handler for an <input/> element:

function Example(props: {}) {
  return <input onChange={(e) => {
    const { value } = e.currentTarget;
    console.log(value);
  }} />
}

The code above creates the following error:

Property 'value' does not exist on type 'EventTarget'.ts(2339)

The quickest fix would be to do a typecast:

    const el = (e.currentTarget as HTMLInputElement).value;

but I do not want to add type casts to the application for such a common operation.

What is the correct way to write a form event handler without using typecasts or the any type?

Environment Info:

  • "strict": true in tsconfig.json
  • [email protected]
  • No external typings installed. Using package defaults.
Derayne answered 29/8, 2019 at 13:26 Comment(3)
can you specify which config of typescript you are using, also which @types?Florous
@TalgatSaribayev I have updated the question. Thank you.Derayne
Related: #75768019Outsail
T
6

Disclaimer: I work on Preact.

This is a bug in our current typings for Preact. Those are distributed with the preact npm package itself. Here is an issue in our tracker that is related to that: https://github.com/preactjs/preact/issues/1930

Teeth answered 2/10, 2019 at 6:44 Comment(1)
It looks like although that bug report is still open, the types have been improved at least in part, enough at least that the example in the question no longer causes an error -- the type of currentTarget in their example is now HTMLInputElement as one would expect.Outsail

© 2022 - 2024 — McMap. All rights reserved.