【问题标题】:Right Typescript type for on:change handler in SvelteSvelte 中 on:change 处理程序的正确 Typescript 类型
【发布时间】:2022-11-03 06:17:39
【问题描述】:

我有这个代码:

<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 应该有什么签名?

【问题讨论】:

    标签: typescript svelte


    【解决方案1】:

    事件target 没有您希望的那么具体。在这种情况下,我通常在函数中使用类型断言来解决这个问题。

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

    尽管错误指出应该正确输入currentTarget,但使用它应该也可以:

    function pathChanged(event: { currentTarget: HTMLSelectElement })
    

    【讨论】:

      【解决方案2】:

      我在输入类型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
      }
      

      【讨论】:

        猜你喜欢
        • 2022-10-16
        • 1970-01-01
        • 2021-04-21
        • 2021-12-30
        • 2021-06-02
        • 2021-07-12
        • 2020-02-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多