DEV Community

Caio Vinicius
Caio Vinicius

Posted on

Working with props declaration in Vue 3 + Typescript

In this post I will show you'll how to work with component props in Vue 3 + Composition API using <script setup>, there's few ways to work with it, let's take a look!

Using the defineProps() macro we can declare props like:

1 - Array of strings

<script setup>
const props = defineProps(['foo'])

console.log(props.foo)
</script>
Enter fullscreen mode Exit fullscreen mode

2 - Object syntax

<script setup>
const props = defineProps({
  title: String,
  likes: Number
})

console.log(props.title)
</script>
Enter fullscreen mode Exit fullscreen mode

2.1 - Object syntax with details

<script setup>
const props = defineProps({
     title: {
         type: String,
         required: true,
         default: '---'
     },
})
</script>
Enter fullscreen mode Exit fullscreen mode

Working with props in Vue 3 with Typescript

Let's see how to declare props in Vue 3 script setup with Typescript:

1 - Type-based declaration

<script setup lang="ts">
defineProps<{
  title?: string
  likes: number
}>()
</script>
Enter fullscreen mode Exit fullscreen mode

In this case we have title and likes props, title is optional and likes is an required prop.

2 - Type-based declaration with default props values

<script setup lang="ts">
 withDefaults(defineProps<{
   title?: string
   likes: number,
 }>(), {
     // here we have default values
     title: '---',
 })
</script>
Enter fullscreen mode Exit fullscreen mode

3 - Advanced types with PropType

For use PropType interface you need to import it from vue:

<script setup lang="ts">
import { type PropType } from 'vue'

export interface Book {
  title: string
  author: string
  year: number
}

const props = defineProps({
    book: {
        type: Object as PropType<Book>,
        required: true,
    }
})
</script>
Enter fullscreen mode Exit fullscreen mode

That's it!

If you want to read and learn more details about component props declaration, please make sure to visit the Vue 3 official documentation about props.

See'ya!

Discussion (0)