lejhbah
lejhbah

Reputation: 1171

Vue 3 + typescript : type check props in single file component

I've seen in the Vuetify and somewhere else that is possible to add a type check for the prop in the template tag.

Lets say we have a button component

<template>
    <div>
        <button>{{ label }}</button>
    </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';

export default defineComponent({
    props: {
        label: { type: String as () => string, default: '' },
    },
});
</script>

Now in the parent component:

<button-component :label="true" />

I will get a compiler warning from the Vue itself that it is wrong parameter, but is it possible to check while typing the code? If not, what is the point of specifying ts type in the props?

Upvotes: 4

Views: 2975

Answers (2)

Sweet Chilly Philly
Sweet Chilly Philly

Reputation: 3219

If you want to hand in a String, and not a boolean you can do the following:

<button-component :label="`true`" />

Because you are binding then the vue compiler is converting your true value into a boolean. So explicitly define a string input here.

Upvotes: 0

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

Based on the Typescript support docs the type:String is sufficient and you could add a validator if you need :

export default defineComponent({
    props: {
        label: { 
          type: String ,
          default: ''
          },
    },
});

You could also do :

export default defineComponent({
    props: {
        label: {
          type: String as PropType<string>,
          default: ''
          },
    },
});

i think the syntax that you're using is for function check type.

Upvotes: 1

Related Questions