使用 Preact + Typescript 的类型安全事件处理程序

Ric*_*ick 7 typescript preact

我正在使用 Preact 编写一个简单的组件,它使用元素onChange的处理程序<input/>

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

上面的代码会产生以下错误:

Property 'value' does not exist on type 'EventTarget'.ts(2339)
Run Code Online (Sandbox Code Playgroud)

最快的解决方法是进行类型转换:

    const el = (e.currentTarget as HTMLInputElement).value;
Run Code Online (Sandbox Code Playgroud)

但我不想为这样的常见操作添加类型转换到应用程序。

在不使用类型转换或类型的情况下编写表单事件处理程序的正确方法是什么any

环境信息:

  • "strict": true在 tsconfig.json 中
  • preact@8.5.2
  • 没有安装外部类型。使用包默认值。

mar*_*ter 6

免责声明:我从事 Preact 工作。

这是我们当前的 Preact 类型中的一个错误。这些是随preactnpm 包本身一起分发的。我们的跟踪器中有一个与此相关的问题:https://github.com/preactjs/preact/issues/1930