When vue3 v-for traverses the data received by defineProps or props, it reports "xx" is of type 'unknown'

Project scenario:

ts is used in vue, and when props or defineProps are used for parent-to-child transmission, v-for traverses the received array, and reports "xx" is of type 'unknown' when fetching values


Problem Description


Cause Analysis:

Tip: Errors caused by ts type deduction


Solution 1: Use interfaces for type declarations

Tip: use the interface for

<script setup lang="ts">

interface ITable {
    date: String,
    name: String,
    address: String,
    phone?: Number,
}
interface IColumns {
    prop: String,
    label: String,
    type?: String,
    width?: String | Number,
}
defineProps<{ columnData: IColumns[], tableData: ITable[] }>()

</script>

Solution 2: Use vue3's type PropType

Tip: Create a ts file, put the type data, and refer to it in the used page           

import { defineProps, type PropType } from 'vue'
import type { TypeColumn } from './index'   // PS:这里引入要写前面type
 
const props = defineProps({
    tableData: {
        type: Array,
        default: () => [],
        require: true
    },
    columnData: {
    type: Array as unknown as PropType<[TypeColumn]>,  // 需要先定义unknown 
    default: () => []
  }
})

 Solution 3: Set the accepted data as any type

const props = defineProps({
    columnData:{
        type: Array<any>,
        default:() =>[],
        require: true
    }
})

Summary: The first two have a disadvantage, which is not conducive to the packaging of components;

The third is convenient for component encapsulation, but loses specific type deduction

Guess you like

Origin blog.csdn.net/qq_38325751/article/details/130046786