Reputation: 475
That I want to do is create a computed value in order to use on my view so as this Documentation I try:
I have a component where I send an array object as:
const tabs = ref([
{
imageSrc: '/programs/test1.png',
....
},
And in other component I receive it as :
export default defineComponent({
name: 'ProgramModal',
props: {
tabs: {
type: Array as PropType<Array<any>>,
required: true,
},
},
computed: {
img() {
return `./images/modal/${encodeURIComponent(this.tabs.imageSrc)}.png`
},
},
})
As you can see I have a computed value that is throwing two errors, one in img
and the other in this.tabs.imageSrc
:
First error:
img implicitly has return type any because it does not have a return type annotation and is referenced directly or indirectly in one of its return expression
Second error:
Property tabs does not exist on type { img(): any; }
What am I doing wrong? Regards
Upvotes: 1
Views: 602
Reputation: 138276
There are two issues:
TypeScript support for the Options API has a known limitation that requires annotating return types on computed
:
Because of the circular nature of Vue’s declaration files, TypeScript may have difficulties inferring the types of certain methods. For this reason, you may need to annotate the return type on methods like
render
and those incomputed
.
So you should annotate the return type of img()
:
img(): string {
👆
return `...`
}
Without fixing this error, type inference for the component instance will be broken, leading to the error you observed: Property tabs does not exist on type { img(): any; }
.
As pointed out in a deleted answer here, this.tabs
is an array, but your computed prop tries to read imageSrc
directly from the array when it really should be from an array element. To read the first array element's imageSrc
, use square brackets with the zero index (this.tabs[0].imageSrc
):
return `./images/modal/${encodeURIComponent(this.tabs[0].imageSrc)}.png`
👆
Your code should look similar to this:
export default defineComponent({
computed: {
img(): string {
return `./images/modal/${encodeURIComponent(this.tabs[0].imageSrc)}.png`
},
},
})
Upvotes: 2