Struggling to accurately define the interface TS2339: The property 'x' is not found on type 'y' when utilizing a Vue ref

Having some trouble with defining issues related to TypeScript in Vue. An error message

TS2339: Property 'product' does not exist on type '(LineItem[] | undefined)[K]'.
keeps popping up. I'm uncertain whether it's due to the line
'orderedItems': Array<LineItem>
or if it has something to do with how I am setting the ref value and using it in the component.

When inspecting purchaseInfo.value?.orderedItems in the console log, I notice that the deep object is still wrapped in a proxy and not properly unwrapped.

<script setup lang="ts">

interface LineItem {
  'product': {
    'id': number,
    'sku': string,
    'title': string,
    'price': string,
    'image': string,
    'description': string,
  },
  'quantity': number;
}

export interface PurchaseInfo {
  'address': string,
  'city': string,
  'zipCode': string,
  'orderedItems': Array<LineItem>,
  'orderStatus': string
}

let purchaseInfo = ref<PurchaseInfo | undefined>();

onMounted(async () => {
  // this function fetchPurchaseInfo() returns a Promise<PurchaseInfo> which is return response.data as PurchaseInfo;
  purchaseInfo.value = await fetchPurchaseInfo() 
})

</script>
<template>
  <div v-if="purchaseInfo">
    <tr v-for="(item, index) in purchaseInfo?.orderedItems">
      <th scope="row">{{ index + 1 }}</th>
      <td>{{ item.quantity }}</td>
      <td>{{ item.product.title }}</td>
    </tr>
</div>
</template>

Answer №1

When initializing a ref without value, it defaults to being undefined. This also impacts the type definition, making purchaseInfo actually of type

Ref<PurchaseInfo | undefined>
.

To handle the loading state in the template when purchaseInfo is still empty, you can simply add a check:

<template>
  <table v-if="purchaseInfo">
    <tr v-for="(item, index) in purchaseInfo.orderedItems"></tr>
  </table>
  <div v-else>
    You can insert a loader here, or display nothing at all.
  </div>
</template>

Answer №2

Unfortunately, I'm not sure how this issue got resolved. It appears that the compiler was continuously detecting an error but eventually started generating code correctly.

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

Return true for cucumber datatable in typescript without fail

I am facing an issue where the following step definition always returns true even for incorrect data from the dataTable. Can someone assist me in correcting the syntax in TypeScript with Chai assertions? Then(/^Verify the following details in report$/, a ...

A step-by-step guide on accessing the data from an uploaded JSON file in a React application

One exciting feature is the drag and drop component that allows users to add multiple files. However, there seems to be an issue with displaying the content of a JSON file once it's added. Below is the code snippet in question: if (files?.length) ...

Transferring an array of objects from a constant to a new array

Attempting to generate an array for passing a prop to another component. const createArrayList = (): ArrayList[] => { let remaining: number = 0 let stateArrayList: String[] = [] for (let i = 0; remaining > i; i++) { stateArrayList.push("Blah") } ...

Encountering CORS Error while trying to access Guest App in Virtualbox using Vue, Express, and Axios

I encountered an issue while trying to access my Vue app in Virtualbox from the host, both running on Linux Mint 20. Although I can now reach the login page from my host, I am consistently faced with a CORS error during login attempts: Cross-Origin Request ...

Resolve functionality in UI Router fails to function properly when utilizing component-based states

Issue: In a project I am currently involved in, there is a component that is utilized in two different scenarios. One instance involves calling it from the Material Design system's bottomSheet, while the other requires direct usage through the ui-ro ...

Vuejs allows objects to trigger the execution of methods through elements

My goal is to utilize a function in order to individually set the content of table cells. In this specific scenario, I aim to enclose the status with the <strong> - Tag (I refrain from modifying the template directly because it is stored within a com ...

What is the best way to bring a closing </div> tag closer to its opening <div> tag in React, Angular, or Vue

Introduction Experienced JavaScript developers may cringe at the sight of a lengthy 200-line function. Their goal is to break it down into smaller, more manageable functions, each around 20 lines long. The idea is for a function to fit on one screen witho ...

regex execution and testing exhibiting inconsistent behavior

The regex I am using has some named groups and it seems to match perfectly fine when tested in isolation, but for some reason, it does not work as expected within my running application environment. Below is the regex code that works everywhere except in ...

What is the best way to incorporate resources from a different location in an Angular project?

I am facing an issue with the deployment time of my server as I am using @angular/localize to support three languages in my application. Despite all locales sharing the same assets, they are being downloaded and deployed individually for each one. To addr ...

Struggling to determine data type in Typescript

My goal is to create an interface for my realm Database using TypeScript. Essentially, I have an automation bot and I want to monitor and track how users are utilizing it. To achieve this, I have designed specific schemas that will be integrated into an i ...

a numeric value ranging between 0 and 1 designated as a data type in Typescript

Is it possible to define a type in TypeScript that is between 0 and 1, or any other integer values? For example: interface Config { opacity: 0.5 // example value } ...

Leveraging vue-devtools in combination with the composition-api while implementing a render function (such as JSX)

Ever since I made the transition to utilizing the composition-api and incorporating a render function (primarily leveraging JSX with TypeScript for type safety within the template), I've encountered an issue where vue-devtools cannot inspect the compu ...

Enhance your Vuetify date picker by incorporating tooltips on disabled days

Is it possible to add tooltips to disabled days when using Vuetify's date picker? I've looked through the documentation but couldn't find a solution. ...

Utilizing Apollo and Vue.js to make GraphQL queries with multiple aliases

My Strapi backend is causing me some trouble as I attempt to fetch data from a single collection type into my Vue.js project using Apollo. Everything works smoothly with a single alias, but I'm facing difficulties when trying to work with multiple ali ...

Can Typescript React Components be created separately for integration into older html applications?

Exploring methods to transition away from outdated front ends by utilizing micro front ends. If I have a React Component Library with Typescript, is it viable to construct the components one by one in order to import them into the existing html/js applica ...

Omit the use of "default" when importing a JSON file in Vite+React with Typescript

Each time I attempt to import a JSON file, it seems to enclose the JSON within a "default" object. When trying to access the object, an error message displays: Property 'default' does not exist on type... I have already configured resolveJsonMod ...

Encountering a Next.js event type issue within an arrow function

After creating my handleChange() function to handle events from my input, I encountered an error that I'm unsure how to resolve. Shown below is a screenshot of the issue: https://i.sstatic.net/fWJA2.png I am currently working with Next.js. In React ...

BotFramework-Webchat Middleware: defining custom CSS class names

My goal is to dynamically assign CSS class names based on the card type to the corresponding HTML element. I've achieved this by utilizing the [AdaptiveCard.customCssSelector] 1 attribute. For example, you can simply include builder.card.customCssSel ...

Why is typescript-eslint flagging the error "Unsafe call of an any typed value" whenever I try to use the delete or update methods?

type TResultCategory<T> = { title: string; items: T[]; description?: string; delete(dispatch: Dispatch<{}>): void; update?(dispatch: Dispatch<{}>, products: TCartProduct[]): void; } type TResult = (TResultCategory<TResultPro ...

Two arrays with similar content connecting links to each other

Two sets of data are being received from an Ajax request. The first set consists of titles that I own, while the second set contains all existing titles along with their respective URLs. My goal is to link the titles in the first set to the URLs found in t ...