Search code examples
typescriptformsvue.js

In Vue with TypeScript, SubmitEvent handler is not assignable


I'm using Vue with TypeScript and I want to assign a submit handler function to my form's submit event. Here's my component:

<script setup lang="ts">
    function handleSubmit(e: SubmitEvent) {
        console.log(`Submitted: ${e.defaultPrevented}`);
    }
</script>

<template>
    <div>
        <h4>Create new</h4>
        <div>
            <form @submit.prevent="handleSubmit">
                <button type="submit">Submit</button>
            </form>
        </div>
    </div>
</template>

However, Volar in VS Code gives me an error for submit.prevent saying:

Type '(e: SubmitEvent) => void' is not assignable to type '(payload: Event) => void'. Types of parameters 'e' and 'payload' are incompatible.ts(2322)

What am I supposed to do here? The function does indeed receive a SubmitEvent yet TS says that the type is wrong.


Solution

  • SubmitEvent interface is based on Event interface. Thus, you can cast Event to SubmitEvent;

    function handleSubmit(e: Event) {
        const event = e as SubmitEvent;
        console.log(`Submitted: ${event.defaultPrevented}`);
    }