Reputation: 157
I am trying to pass props from parent component to child in Vue.js.
In the parent component,
<template>
<child v-for="(folder, idx) in folders" :key="idx" :folder="folder">
</child>
</template>
<script lang="ts">
import {ref, defineComponent} from "vue";
import Child from "../components/Child.vue";
interface Folder {
id: number,
name: string | null,
}
export default defineComponent({
name: "Parent",
components: {Child},
setup(){
const folders = ref<Folder[]>()
folders.value = [
{
id: 1,
name: "aaa"
},
{
id: 2,
name: "bbb"
}
]
return {folders}
}
})
In the child component,
<template>
<p>{{folder.name}}</p>
</template>
<script lang="ts">
import {defineComponent} from "vue";
interface Folder {
id: number,
name: string | null,
}
export default defineComponent({
name: "Child",
props:{
folder: Object as PropType<Folder>,
},
setup(){
return {}
}
})
With the following error code I get
Argument of type 'Folder | undefined' is not assignable to parameter of type 'Folder'. Type 'undefined' is not assignable to type 'Folder'.ts(2345)
How to solve this error?
Upvotes: 1
Views: 1963
Reputation: 104
You should replace the props section of your code with the following:
props: {
folder: {
type: Object as PropType<Folder>,
required: true,
}
},
This way undefined
will not be considered as an option to be assigned to the Folder type.
This happens because all props are optional, and an absent optional prop will have undefined
value according to the docs: https://vuejs.org/guide/components/props.html#prop-validation
Upvotes: 1