简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM