The computed value fails to identify the prop object

I am trying to create a computed value that I can use in my view by following this documentation:

Within a component, I am sending an array object like this:

const tabs = ref([
      {
        imageSrc: '/programs/test1.png',
         ....
      },

In another component, I am receiving it like this:

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`
    },
  },

})

However, I am encountering two errors with the computed value. The first error states:

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

The second error says:

Property tabs does not exist on type { img(): any; }

Can anyone help me figure out what I am doing wrong? Thanks.

Answer â„–1

There are a couple of issues you need to address:

  1. The Options API for TypeScript has a known limitation that requires annotating return types on computed:

    Due to the circular nature of Vue’s declaration files, TypeScript might struggle to infer types for certain methods. As a result, you may have to specify the return type for methods like render and those in computed.

    Make sure to annotate the return type of img():

    img(): string {
              👆
      return `...`
    }
    

    If you don't fix this issue, type inference for the component instance will be incorrect, causing the error message:

    Property tabs does not exist on type { img(): any; }
    .

  2. One user pointed out in a removed answer that this.tabs is an array, but your computed property is trying to access imageSrc directly from the array instead of an element within the array. To access the imageSrc of the first element in the array, use square brackets with index zero (this.tabs[0].imageSrc):

    return `./images/modal/${encodeURIComponent(this.tabs[0].imageSrc)}.png`
                                                          👆
    

Your revised code should resemble something like this:

export default defineComponent({
  computed: {
    img(): string {
      return `./images/modal/${encodeURIComponent(this.tabs[0].imageSrc)}.png`
    },
  },
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Triggering an event in Angular 2 after ngFor loop completes

I am currently attempting to utilize a jQuery plugin that replaces the default scrollbar within dynamic elements in Angular 2. These elements are generated using an ngFor loop, making it impossible to directly attach jQuery events to them. At some point, ...

Encountering a runtime issue with socket.io when using typescript that has been bundled by

Recently, I attempted to implement web sockets using socket.io in a Node server written in TypeScript with ExpressJS and bundled with Webpack. The server code is structured as follows: import * as Express from "express"; import * as SocketIO from "socket ...

Having trouble locating variables in VueJS3 when using Axios and TypeScript?

I am facing an issue where I am unable to access the this.somethingHere variables inside methods using axios in combination with vuejs3 and TypeScript. Template code (not required): <template> <div> <form> <label for=" ...

ReactTS: Setting a default generic for dynamic components

Just a follow-up to my previous question: Is it possible to extend type by dynamic Component Props in React with TypeScript? Consider the following code snippet: type Base = { baseProp: ... } type Extend = { extendProp: ... } // use this if "as ...

How can I incorporate Vue draggable feature in my project using cards?

I've been attempting to integrate vuedraggable with Vuetify Cards, but I'm facing an issue where the drag and drop functionality doesn't seem to work when the cards are in a single row. Interestingly, it works perfectly fine when they are di ...

Leveraging the power of CSS calc() in combination with TailwindCSS styles and JavaScript

Can you explain why applying styles with TailwindCSS v3 to calculations using JS variables does not work? I'm working on a project using VueJS, and I've noticed that styling works fine when using calc as a string like this: ... <div class=&qu ...

"Encountering difficulties while setting up an Angular project

I am currently working on setting up an Angular project from scratch. Here are the steps I have taken so far: First, I installed Node.js Then, I proceeded to install Angular CLI using the command: npm install -g @angular/cli@latest The versions of the ...

In Laravel, the collection will consistently provide an object as opposed to an array

I am currently working on a news page that is being loaded with Vue and Vue Isotope. The challenge I'm facing is related to the data format required by Vue Isotope, which needs my data to be in an array so that I can add more articles to the isotope w ...

Is there a way to allocate a prop to data just once?

I need assistance with an element <input type="text" class="text-[16px] text-light-text bg-main-background p-[11px]" name="email" ref="email" ...

Utilizing External Store Module Getters/Actions/Mutations in Vuex 4 with TypeScript

In my Vue 3 project with TypeScript and Vuex4, I am currently using a boilerplate method for declaring store modules in vuex with TypeScript. The code snippet I am using can be found at: //#region Store export const state: State = { stateVar: null, ...

Stop unwanted clicking on inactive buttons in Angular

I want to make sure that disabled buttons cannot be clicked by users who might try to remove the disabled attribute and trigger an action. Currently, I have this code to handle the situation: <button [disabled]="someCondition" (click)="executeAction()" ...

Tips for verifying the presence of a specific value within an array of union types

Given an array of a specific union type, I am trying to determine if a string from a larger set that includes the union type is present in the array during runtime: const validOptions: ("foo" | "bar")[] = ["foo", "bar"] type IArrType = typeof validOptions ...

Sharing data between parent and child components in a Vue dialog box

Trying to pass batch_code data from the parent component dashboard.vue to the child component review.vue. The dashboard has details like batch_code, but I'm facing issues passing this data to the review component. The idea is for the review component ...

Exploring how to traverse a <router-outlet> within its container

I am attempting to switch the active component within a from its parent. After observing how Ionic achieves this, I believe it should resemble the following (simplified): @Component({ template: '<router-outlet></router-outlet>' } ...

Tips for displaying placeholder in cropper following an upload

I am currently working with vue-cropper 4.1 using cropperjs in combination with Nuxt 2.13. When my cropper loads, it displays a placeholder image. However, after choosing and uploading a new image, the cropper still shows the previously chosen image instea ...

Discovering potential types in Typescript through optional inference

Uncertain if the question is formulated correctly, but I am attempting to deduce the result type without knowing exactly how to achieve it. This is my current approach: type StateSetter<S> = (prevState: S) => S; type ResolvableHookState<S> ...

Issue with bootstrap modal new line character not functioning properly

Is there a correct way to insert a new line for content in a modal? I have this simple string: 'Please check the Apple and/or \nOrange Folder checkbox to start program.' I placed the '\n' newline character before "Orange," e ...

Incorporate a Font Awesome icon link within ReactJS for enhanced design and functionality

I am using Typescript and ReactJS to work on adding a link to font awesome icons. Below is a snippet of my code: import React from 'react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faRandom } from &apos ...

Vue with TypeScript encountering error: property does not exist on type

As I work on converting my JavaScript code to TypeScript, I have encountered an issue. My conversion attempt is shown below. <script lang="ts"> export default { data() { return { isShow: false as boolean } }, methods: { ...

Create a typescript class object

My journey with Typescript is just beginning as I delve into using it alongside Ionic. Coming from a background in Java, I'm finding the syntax and approach quite different and challenging. One area that's giving me trouble is creating new object ...