Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js, Typescript and VeeValidate typing

I'm trying to have build a vue.js project strictly typed with Typescript.

I use VeeValidate to build a form. I use a reference to the VeeValidate ValidationObserver to process the submitted form. I also use vue-class-component.

Here is how I tried to type the ValidationObserver component in my code.

<template>
  <ValidationObserver tag="form" ref="repertoireForm" @submit.prevent="submitForm">
    <ValidationProvider rules="required"></ValidationProvider>
  </ValidationObserver>
</template>


<script lang="ts">

import Vue from 'vue';
import Component from 'vue-class-component';
import {ValidationObserver, ValidationProvider} from 'vee-validate';

@Component({
  components: {
    ValidationObserver,
    ValidationProvider,
  },
})
export default class RepertoireForm extends Vue 
  $refs!: {
    // here is what I'm trying to type
    repertoireForm: ValidationObserver,
  }

  async submitForm(e: Event): Promise<void> {
    const valid = await this.$refs.repertoireForm.validate();

    // some submit routine here
  }
}
</script>

When I try to compile this, I got the following error:

TS2749: 'ValidationObserver' refers to a value, but is being used as a type here.

How can I correctly type this repertoireForm $refs ?

like image 267
Nicolas Appriou Avatar asked Dec 23 '22 21:12

Nicolas Appriou


1 Answers

The imports you want are actually ValidationProviderInstance and ValidationObserverInstance as without the Instance these refer to a Component.

import { ValidationProviderInstance, ValidationObserverInstance } from 'vee-validate'

And then later:

const valid = await (this.$refs.repertoireForm as ValidationObserverInstance).validate()

Edit

v3 has changed things. You can now use the InstanceType:

$refs!: {
    validationProviderRef: InstanceType<typeof ValidationProvider>,
    validationObserverRef: InstanceType<typeof ValidationObserver>
}
like image 50
Ohgodwhy Avatar answered Jan 10 '23 16:01

Ohgodwhy