<" /> <" /> <"/>

How can I export an array in Vue so that the child component will know what kind of properties each element have?

25 Views Asked by At

I am learning Vue.

Here is the parent element

<template>
  <Header />
  <div class="container">
    <IncomeExpenses :income="+income" :expense="+expense" />
    <TransctionList :transactions="transactions" />
  </div>
</template>

<script setup lang="ts">
import Header from "./components/Header.vue";
import IncomeExpenses from "./components/IncomeExpenses.vue";
import TransctionList from "./components/TransctionList.vue";

import { ref, computed, defineComponent } from "vue";

export interface TransactionInterface {
  id: number;
  text: string;
  amount: number;
}

const transactions: TransactionInterface[] = ref([
  { id: 1, text: "Flower", amount: -19.99 },
  { id: 1, text: "Salary", amount: 299.99 },
  { id: 1, text: "Book", amount: -10 },
  { id: 1, text: "Camera", amount: 150 },
]);

const total = computed(() => {
  return 1+2
});

// Get Income
const income = computed(() => {
  return 4
});

// Get Expense
const expense = computed(() => {
  return 3
});

</script>

I am passing transactions as props to TransctionList components

Inside the List component I am just looping and showing them

<li
      v-for="transaction in transactions"
      v-bind:key="transaction.id"
      :class="transaction.amount > 0 ? 'plus' : 'minus'"
    >
      {{ transaction.text }}
      <span> ${{ transaction.amount }} </span
      ><button class="delete-btn">x</button>
    </li>

<script setup lang="ts">
import { defineProps } from "vue";


const props = defineProps({
  transactions: {
    type: Array,
    required: true,
  },
});

const myFunction = () => {
  return 3;
};
</script>

The thing is i am getting warning on the word transaction saying that 'transaction' is of type 'unknown'. How can i fix this warning?

1

There are 1 best solutions below

2
Billuc On

With your current code, in TransactionList.vue, transaction is defined as a property of type Array with is interpreted as unknown[].

One way to specify the type is to use the generic (TS) version of defineProps

<script setup lang="ts">
interface Props {
  transactions: { id: string, amount: number, text: string }[];
}

const props = defineProps<Props>()
</script>

see https://vuejs.org/guide/typescript/composition-api