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.
A. Props should not use union with undefined; use optional instead.
B. Missing default value for name prop.
C. defineProps must be called without type arguments.
D. The prop name must be a number, not string.
Solution
Step 1: Understand how to mark optional props
In Vue with TypeScript, optional props should be marked with ? instead of union with undefined.
Step 2: Identify the incorrect typing
Using string | undefined is allowed but not recommended; better to write name?: string for optional props.
Final Answer:
Props should not use union with undefined; use optional instead. -> Option A
Quick Check:
Use ? for optional props, not union with undefined [OK]
Hint: Use ? to mark optional props, not union with undefined [OK]
Common Mistakes:
Using union with undefined instead of ?
Forgetting to mark optional props
Confusing default values with typing
5. You want to type a Vue component prop named items that accepts an array of objects with a required id (number) and optional label (string). Which is the correct TypeScript type for defineProps?
hard
A. defineProps<{ items?: Array<{ id: number; label: string }> }>()
B. defineProps<{ items: { id: number; label?: string }[] }>()
D. defineProps<{ items: Array<{ id: number; label: string }> }>()
Solution
Step 1: Understand the prop structure
The prop items is an array of objects. Each object must have a required id (number) and an optional label (string).
Step 2: Choose the correct typing
defineProps<{ items: { id: number; label?: string }[] }>() correctly types items as an array of objects with id: number and optional label?: string. The prop itself is required.