Here is what I learned from having spent quite a bit of time when trying and using defineProps
with Vue 3 and TypeScript.
As a remind, using the JavaScript, props are defined the following way:
|
|
However, using TypeScript, when the prop is required, it becomes:
|
|
Notice the prop type isn’t the same: String
in JavaScript vs. string
in TypeScript. It’s important to follow that usage so the code works. And if you don’t, ESLint will make sure to tell when writing in TypeScript.
And when you need to set a prop as non-required (implicitly, they’re required…), use the ?
following the prop name:
|
|
Now, it will get more complex when you need to set defaults.
Before, using JavaScript and the Option API, you would write:
|
|
Or if you prefer the Composition API, it would look this:
|
|
Note: you can destructure the props easily with { propName }
as shown above.
Using TypeScript and the composition API, you will need to use withDefaults
macro and create an interface to define the props:
|
|
So let’s break down the code:
title
andbody
are string props and they’re optional.- then (1) instantiate the props by providing to the
withDefaults
macro thedefineProps
macro typed with the interface and (2) add an object with all the props you need to define a default value for.
In the example, not providing a default value would mean the props would both equal to undefined
because of the ?
.
With explicit defaults, they will equal to an empty string.
You don’t have to define a default for all props and they don’t need to be flagged as optional to receive a default value.
Finally, when I recommend to use the interface declaration when you have many props and extract this interface to a separate file that you will simply import in your component. To me, that makes the component’s code cleaner.
Do you have questions on the topic? Read the official documentation or ask away!