Validating your Vue Props like a Pro
Vue requires to explicit declare any data passed to a component as props. Additionally, it provides a powerful built-in mechanism to validate this data. This acts as a contract between the component and the consumer and ensures that the component is used as intended.
Let's explore this powerful tool which can help us reduce bugs and increase our confidence during development and debugging.
Validating primitive types is as easy as setting the type option to the primitive type constructor.
Complex types can also be validated in the same way.
type can be one of the following values:
type can also be a custom class or constructor function, and the assertion will be made with an
instanceof check. For example, given the following class:
You could use it as a prop type like this:
Props support the usage of a validator function. This function accepts the raw value of the prop and must return a boolean to determine if this prop is valid or not.
Using enums ✨
Sometimes you want to narrow the values down to a specific set which can be done by faking an enum like this:
Which can be imported and used in both the validator and as a default value.
Lastly, the parent component can also import and use this enum that eliminates the usage of magic strings from our application.
ℹ️ Symbols is an alternative way to define enum values, when casting to a string is not needed. [example]
Boolean props have unique behaviour. The existence or absence of the attribute can determine the prop value.
Combining Vue's built-in prop validation with TypeScript can give us even more control over this mechanism since TypeScript natively supports interfaces and enums.
We can use an interface and the
PropType utility to annotate complex prop types. This ensures that the passed object will have a specific structure.
Real enums ✨
All the above are valid when using Vue 3 with either Options or Composition API. The difference is when using
<script setup>. Props have to be declared using the
defineProps() macro like this:
Or when using TypeScript with
<script setup>It's possible to declare props using pure type annotations:
Or using an interface:
Finally, declaring default values when using the type-based declaration:
Type checking is a great first line of defence against bugs as your application grows in size. Vue's built-in prop validation is compelling. Combined with TypeScript, it can give you high confidence in properly using a component interface, reducing bugs and improving the overall code quality and development experience.