Vue Tip: Validate Props in Script Setup With TypeScript
You can define prop validations for your component in the <script setup>
using the defineProps()
compiler macro. This is a great way to ensure that the props you receive are of the correct type and shape.
Without TypeScript
Let's first take a look at the official example from the Vue docs without using TypeScript:
1<script setup>
2defineProps({
3 // Basic type check
4 // (`null` and `undefined` values will allow any type)
5 a: Number,
6 // Multiple possible types
7 b: [String, Number],
8 // Required string
9 v: {
10 type: String,
11 required: true,
12 },
13 // Number with a default value
14 d: {
15 type: Number,
16 default: 100,
17 },
18 // Object with a default value
19 e: {
20 type: Object,
21 // Object or array defaults must be returned from
22 // a factory function. The function receives the raw
23 // props received by the component as the argument.
24 default(rawProps) {
25 return { message: 'hello' };
26 },
27 },
28 // Custom validator function
29 // full props passed as 2nd argument in 3.4+
30 f: {
31 validator(value, props) {
32 // The value must match one of these strings
33 return ['success', 'warning', 'danger'].includes(value);
34 },
35 },
36 // Function with a default value
37 g: {
38 type: Function,
39 // Unlike object or array default, this is not a factory
40 // function - this is a function to serve as a default value
41 default() {
42 return ['one, two'];
43 },
44 },
45});
46</script>
With TypeScript
Now let's rewrite the same example using TypeScript inside <script setup>
:
1<script setup lang="ts">
2interface Props {
3 a?: number;
4 b?: string | number;
5 c: string;
6 d?: number;
7 e?: { message: 'string' };
8 f?: 'success' | 'warning' | 'danger';
9 g?: Array<string>;
10}
11withDefaults(defineProps<Props>(), { d: 100, e: { message: 'hello' }, g: () => ['one', 'two'] });
12</script>
All we need to do is define an interface for the props and use the withDefaults
helper to set default values. TypeScript will take care of the rest.
StackBlitz
Try it yourself on StackBlitz:
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Nuxt Tip: How Nuxt Uses Nitro, h3 and ofetch Internally
Nitro, h3 and ofetch are UnJS packages that are used to power the Nuxt 3 server engine.
Nuxt Tip: Use Environment-Specific Configurations
It sometimes happens that you need to have different configurations for different environments in your Nuxt.js application. Therefore, Nuxt provides fully typed, per-environment overrides for your Nuxt configuration.