我想在打字稿中获取 svelte on:input 事件的事件类型,但我找不到它

问题描述 投票:0回答:3

我有一个 svelte 输入

 <input
    {type}
    {placeholder}
    on:input={(e) => emitChange(e)}
    class="pl-2 w-full h-full bg-sand border border-midnight dark:bg-midnight"
  />

进入这个函数

  function emitChange(event: any) {
    const text = event.target.value
    dispatch("changeContent", {
      text,
    })
  }

我想去掉

any
并将其替换为正确的
InputEvent
,我可以看到它正在使用控制台日志。但我如何从 svelte 中找到
InputEvent

import { createEventDispatcher, InputEvent } from "svelte"
失败并显示
Module '"svelte"' has no exported member 'InputEvent'

我尝试过:

  function emitChange(event: InputEvent) {
    console.log(event, "13rm")
    const text = event.target.value // fails here
  }

这给出了

Property 'value' does not exist on type 'EventTarget'
即使当我控制台日志
event
我看到:

InputEvent {isTrusted: true, data: 'a', isComposing: false, inputType: 'insertText', dataTransfer: null, …}isTrusted: truebubbles: truecancelBubble: falsecancelable: falsecomposed: truecurrentTarget: nulldata: "a"dataTransfer: nulldefaultPrevented: falsedetail: 0eventPhase: 0inputType: "insertText"isComposing: falsereturnValue: truesourceCapabilities: nullsrcElement: input.pl-2.w-full.h-full.bg-sand.border.border-midnight.dark:bg-midnighttarget: input.pl-2.w-full.h-full.bg-sand.border.border-midnight.dark:bg-midnighttimeStamp: 1324.199999988079type: "input"view: nullwhich: 0[[Prototype]]: InputEvent '13rm'

当我单击打开对象时,我会看到一个带有值的

target
属性。像这样:

target: {
    // ...
    value: "a"
}

所以我一定是类型错误。

编辑,这“可以”获取事件类型,但我仍然有可怕的

any

  function emitChange(event: any) {
    console.log(event, "13rm")
    const { value } = event.target as HTMLInputElement // improvement
    const text = value
  }
typescript svelte
3个回答
0
投票

从本机 HTML 元素发出的事件与不使用 Svelte 时发出的事件相同。 Svelte 不会改变这些本地事件。因此,您想要的

input
元素的事件类型是
InputEvent
,不需要导入即可工作。

例如:

function emitChange(event: InputEvent) {
    console.log(event, "13rm")
    const { value } = event.target
    const text = value
}


0
投票

您的编辑几乎是正确的,只需将

any
更改为
InputEvent
:

  function emitChange(event: InputEvent) {
    console.log(event, "13rm")
    const { value } = event.target as HTMLInputElement
    const text = value
  }

0
投票

这适用于当前版本的 Svelte (4.2.7),使用

<script lang="ts">

function inputHandler(event: Event & { currentTarget: EventTarget & HTMLInputElement }) {
    if (!event.target) return;
    const { value } = event.target as HTMLInputElement;
    // use value
}

使用纤细的输入元素作为

<input type="text" on:input={inputHandler} />
© www.soinside.com 2019 - 2024. All rights reserved.