Performance: Typing component props
Typing component props affects development speed and runtime type checking but has minimal direct impact on page load or rendering performance.
const props = defineProps<{ title: string; count: number }>()export default { props: ['title', 'count'] }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Untyped props (string array) | 0 | 0 | 0 | [OK] Good for runtime but risky for bugs |
| Typed props with defineProps | 0 | 0 | 0 | [OK] Best for developer experience |
<script setup lang="ts"> block?defineProps<Type>() where Type is an object type.<script setup lang="ts">:
const props = defineProps<{ count?: number }>()
console.log(props.count ?? 0)
What will be logged if the component is used without passing count?count is optional (marked with ?), so it may be undefined if not passed.props.count ?? 0?? returns the right side (0) if props.count is null or undefined.<script setup lang="ts">
const props = defineProps<{ name: string | undefined }>()
</script>
What is the problem?? instead of union with undefined.string | undefined is allowed but not recommended; better to write name?: string for optional props.items that accepts an array of objects with a required id (number) and optional label (string). Which is the correct TypeScript type for defineProps?items is an array of objects. Each object must have a required id (number) and an optional label (string).items as an array of objects with id: number and optional label?: string. The prop itself is required.Pass the test and this pattern moves unknown