0
0
Vueframework~5 mins

Typing component props in Vue

Choose your learning style9 modes available
Introduction

Typing component props helps you check that the right kind of data is passed to your Vue components. This makes your app more reliable and easier to understand.

When you want to make sure a component only receives specific types of data, like a number or string.
When you want to catch mistakes early by checking props during development.
When you want to document what kind of data a component expects for better teamwork.
When you want to provide default values and validations for props.
When you want to improve code readability and maintainability.
Syntax
Vue
defineProps<{ propName: Type }>()
Use defineProps with a TypeScript type to specify prop types in <script setup>.
This syntax works only in Vue 3 with the Composition API and <script setup>.
Examples
This example types a prop named title as a string.
Vue
<script setup lang="ts">
const props = defineProps<{ title: string }>()
</script>
This example types an optional prop count as a number.
Vue
<script setup lang="ts">
const props = defineProps<{ count?: number }>()
</script>
This example types two props: isActive as boolean and label as string.
Vue
<script setup lang="ts">
const props = defineProps<{ isActive: boolean; label: string }>()
</script>
Sample Program

This component expects a required title prop of type string and an optional count prop of type number. It displays them in the template.

Vue
<template>
  <h1>{{ title }}</h1>
  <p>Count: {{ count }}</p>
</template>

<script setup lang="ts">
const props = defineProps<{ title: string; count?: number }>()
</script>
OutputSuccess
Important Notes

If you pass a prop with the wrong type, TypeScript will show an error during development.

Optional props can be marked with ? in the type.

Always use lang="ts" in <script setup> to enable TypeScript.

Summary

Typing props helps catch errors early and makes your code clearer.

Use defineProps<Type>() inside <script setup lang="ts"> to type props.

Mark props optional with ? if they are not required.