Spelte中on:change处理程序的右 typescript 类型

4xrmg8kj  于 2023-02-17  发布在  TypeScript
关注(0)|答案(2)|浏览(125)

我有这个代码:

<select class="form-control" on:change={pathChanged}>

pathChanged的签名为:

function pathChanged(event: { target: HTMLSelectElement }) {

当我使用npm run check通过tsc运行它时,我得到这个错误:

Error: Type '(event: { target: HTMLSelectElement; }) => void' is not assignable to type 'FormEventHandler<HTMLSelectElement>'.
  Types of parameters 'event' and 'event' are incompatible.
    Type 'Event & { currentTarget: EventTarget & HTMLSelectElement; }' is not assignable to type '{ target: HTMLSelectElement; }'.
      Types of property 'target' are incompatible.
        Type 'EventTarget | null' is not assignable to type 'HTMLSelectElement'.
          Type 'null' is not assignable to type 'HTMLSelectElement'. (ts)

<select class="form-control" on:change={pathChanged}>

pathChanged应该具有什么签名?

vjhs03f7

vjhs03f71#

事件target没有你想象的那么具体,在这种情况下,我通常在函数中使用类型Assert来解决这个问题。

function pathChanged(event: Event) {
   const target = event.target as HTMLSelectElement;
   // ...
}

虽然错误声明currentTarget应该正确键入,所以使用它也应该工作:

function pathChanged(event: { currentTarget: HTMLSelectElement })

如果事件具有比Event更具体的类型,例如MouseEvent,则可以使用&组合这些类型:

function onMouseUp(event: MouseEvent & { currentTarget: HTMLSelectElement })
gtlvzcf8

gtlvzcf82#

我在输入类型file中执行了此操作:

// added this interface
interface FormEventHandler<T> {
    target: EventTarget | null;
}

// then in the function
const onChangeFile = async (event: FormEventHandler<HTMLInputElement>) => {
    const target = event.target as HTMLInputElement;
    // your code
}

相关问题