打字稿的细长事件参数类型

Joh*_*ohn 6 typescript svelte

如此苗条的新手,但它是如此之小,非常适合我正在从事的工作。

去打字稿选项:https : //svelte.dev/blog/svelte-and-typescript

我如何或在哪里可以找到自定义组件事件的类型:

一个简单的登录组件表单:

<script lang="ts">
  import { createEventDispatcher } from 'svelte'

  const dispatch = createEventDispatcher()
  let isSubmitting = false
  const handleSubmit = (e: HTMLFormElement) => {
    e.preventDefault()
    isSubmitting = true
    const payload = {
      username: e.target.username.value,
      password: e.target.password.value,
    }
    dispatch('submit', payload)
  }
</script>

<form on:submit={handleSubmit}>
    <label for="username"><b>Username</b></label>
    <input type="text" placeholder="Enter Username" name="username" required id="username">

    <label for="password"><b>Password</b></label>
    <input type="password" placeholder="Enter Password" name="password" required id="password">

    <button type="submit" disabled={isSubmitting}>Login</button>
</form>

Run Code Online (Sandbox Code Playgroud)

包含在另一个组件中以处理提交:

<script lang="ts">
  import Login from './molecules/Login.svelte'
  const loginHandle = function (a: any) {
    console.log(a)
  }
</script>

<main class="{open}">
   {#if !authenticated}
      <Login on:submit={loginHandle}/>
   {/if}
</main>
Run Code Online (Sandbox Code Playgroud)

现在有一个丑陋的any添加到loginHandle但是当将事件转储到控制台时它看起来非常苗条特定..我在哪里可以找到类型?

Rom*_*kyi 9

我如何或在哪里可以找到自定义组件事件的类型:

您可以将对象传递给函数的泛型createEventDispatcher。其中 key 是自定义事件名称,value 是详细信息对象。

子组件 ( <Calendar />)

<script lang="ts">
  import { createEventDispatcher } from 'svelte'

  const dispatch = createEventDispatcher<{ select: Date }>()

  function onSelect(date: Date): void {
    dispatch('select', date)
  }
</script>

...
Run Code Online (Sandbox Code Playgroud)

父组件

<script>
  function handleSelect (event: CustomEvent<Date>) {
    console.log('Selected date', event.detail)
  }
</script>

<Calendar on:select={handleSelect} />
Run Code Online (Sandbox Code Playgroud)

使用示例

在此输入图像描述


Doo*_*ber 5

对于完整输入,将事件引发器更改为:

const dispatch = createEventDispatcher<{submit:{username:string, password:string}}>()
Run Code Online (Sandbox Code Playgroud)

事件消费者:

const loginHandle = function (a: CustomEvent<{username:string, password:string}>) {
    console.log(a.detail.username) //username is type string
    console.log(a.detail.password) //password is type string
}
Run Code Online (Sandbox Code Playgroud)

这将使 dispatch("submit", "wrongDetailType") 失败。它消除了处理程序中类型为“any”的 a.detail 。


小智 4

Svelte 现在附带 CustomEvent 接口定义。所以你可以如下声明你的函数。

const loginHandle = function (a: CustomEvent) {
    console.log(a)
}
Run Code Online (Sandbox Code Playgroud)

  • 这并不能真正回答问题。即使您使用“CustomEvent”,“detail”属性仍然是“any”。 (2认同)