Home > Software engineering >  Vue 3/Typescript/vscode async submit handlers type error
Vue 3/Typescript/vscode async submit handlers type error

Time:10-30

I have a form in a Vue 3 component and I'm calling an async submit handler:

<template>
  <form @submit.prevent="handleLogin">
    <!-- inputs etc -->
  </form>
<template>
<script setup lang="ts">

// unrelated code...

const handleLogin = async (event: Event) => {
  try {
    await login({ ...form.value });
    resetForm();
  } catch (error: any) {
    console.error(error.error_description || error.message);
  }
  return event
};
</script>

In vscode the @submit is being highlighted with this typescript error:

Type '(event: Event) => Promise<Event>' is not assignable to type 'Event'.ts(2322)
__VLS_types.ts(108, 56): The expected type comes from property 'submit' which is declared here on type 'EventObject<undefined, "submit", {}, Event | undefined>'

The error makes sense, handleLogin returns a Promise<Event> and submit expects an Event.

I just don't know how to resolve (pun intended) this error. How should I invoke an async handler?

CodePudding user response:

When I restarted vscode I saw there was a problem listed in the editor footer. Clicking on it showed:

Error description linking to the volar issue linked above

As shown in the image this was an issue with the Volar VSCode plugin: https://github.com/johnsoncodehk/volar/issues/1985

Upgrading @types/node to 18.11.1 or later would solve it.

Now that I'm confident this isn't an error in my code I will just ignore this error until an underlying Vue ticket is merged.

So I can revert my handler to not using the event:

const handleLogin = async () => {
  try {
    await login({ ...form.value });
    resetForm();
  } catch (error: any) {
    console.error(error.error_description || error.message);
  }
};
  • Related