Two ways of defining props in Typescript
3 quarters ago - 6 min read • #vueProps in Vue are a basic concept of passing values to component from outside/parent. It is one of the first things you come across when learning Vue.
// MyComponent.vue
<script setup lang="ts">
defineProps({
value: {
type: String,
required: true
}
})
</script>
<template>
<div>{{ value }}</div>
</template
And MyComponent
usage:
<script setup lang="ts">
</script>
<template>
<MyComponent value="Hello Wold" />
</template>
So far so clear.
A less known fact is that there are two ways of defining props using Typescript:
- by runtime declaration
- by type declaration
Runtime Declaration
This is the most common way where the props are defined by an object:
// this is the same code as above
<script setup lang="ts">
defineProps({
value: {
type: String,
required: true
}
})
</script>
<template>
<div>{{ value }}</div>
</template
Type Declaration
But there is also another way - defining props by Typescript type:
<script setup lang="ts"></script>
<template>
<div>{{ value }}</div>
</template
What about default values?
With defining props by the Type, you can't define prop default value in the type directly. For such case there is another compiler macro withDefaults
:
withDefaults(defineProps<Props>(), {
value: 'hello'
})
Which one?
I don't see any advantage of one way over the another, but I'm using the runtime declaration though as the defining default type directly in the object seems a bit more clear to me.