I'm using Vue3 with the options API. I have several vue components which use this prop:
exercise: {
type: Object as PropType<Exercise>,
required: true,
},
So I decided to create a sharedProps
object which contains it in order to import it (and any other shared prop) inside the components, without having to define the same prop multiple times:
export const sharedProps = {
exercise: {
type: Object as PropType<Exercise>,
required: true,
},
However, if I import it and use inside of a component like so:
props: {
// component-specific props ...
...sharedProps
}
then, when I try to access this.exercise
inside of my component code, its inferred type is Exercise|undefined
regardless of the fact that the corresponding prop has required: true
.
In addition to just my IDE reporting the error, the build process also fails.
If I add the prop to the component code directly, that is without importing it, its type is correctly inferred as Exercise
.
One more thing I noticed is that, if I provide a default
to the prop, the issue goes away. My understanding, however, is that required: true
should be enough for it to not be inferred to be an optional property.
Why does this happen if I import the props from an external file?
@Estus Flask is right!
<script lang="ts">
import { defineComponent, PropType } from "vue";
type Exercise = {
day: number
}
const sharedProps = {
exercise: {
type: Object as PropType<Exercise>,
required: true as const,
},
}
export default defineComponent({
props: {
time: String,
...sharedProps
}
})
</script>
<template>
<h1>{{ exercise.day }}</h1>
</template>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.