English 中文(简体)
Trouble defining interface correctly TS2339: Property x does not exist on type y and with using a vue ref
原标题:

I am having trouble with some defining issues with typescript in Vue. I am getting TS2339: Property product does not exist on type (LineItem[] | undefined)[K] . I am not sure if it doesn t like orderedItems : Array<LineItem> or if the way I am setting the ref value and using it in the component.

I notice that when I console log purchaseInfo.value?.orderedItems that deep object is still in a proxy and not unwrapped properly.

<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>
问题回答

When you create a ref without initial value it is undefined by default. This also affects the type, so purchaseInfo is actually Ref<PurchaseInfo | undefined>.

So you just need a check in the template to handle the loading state, when purchaseInfo has no value yet:

<template>
  <table v-if="purchaseInfo">
    <tr v-for="(item, index) in purchaseInfo.orderedItems" />
  </table>
  <div v-else>
    You can put some loader here, or render nothing.
  </div>
</template>

I wish I can say what fixed this. It looks like the compiler kept picking up on something bad and decided to start building fine.





相关问题
store data in memory with nestjs

I am trying to persist some data in my nestjs server so I can then use that data in my client app through http requests. I have created a products.service.ts file with the function getAllData() that ...

React Hook Form Error on custom Input component

I am having a problem when I use react hook form + zod in my application, in short the inputs never change value and I get the following error in the console: Warning: Function components cannot be ...

Updatable promises using proxy in JavaScript

EDIT: I ve updated this question, and the old question is moved here. A POC can be found on this jsfiddle or the snippet below GOAL: The goal here is to make or rather simulate a promise that can be ...

热门标签